Регулярно приходится писать и ревьюить код, где используется PySide2-6.
Заметил, что в подавляющем большинстве случаев настройка создаваемых базовых виджетов происходит через методы. Думаю, всем знаком такой способ.
Простой пример с кнопкой:
button = QPushButton("Click Me")
button.setMinimumWidth(300)
button.setFlat(True)
button.setStyleSheet("font-size: 20pt")
button.setToolTip("Super Button")
button.clicked.connect(lambda: print("Button clicked"))
Но есть и альтернативный способ - настройка через свойства. Это просто ключевые аргументы конструктора класса. Хоть они и не указаны в документации как аргументы, но они есть)
Этот код делает тоже самое но с помощью Property
button = QPushButton(
"Click Me",
minimumWidth=300,
flat=True,
styleSheet="font-size: 20pt",
toolTip="Super Button",
clicked=lambda: print("Button clicked"),
)
Где это может быть полезно
▫️ Это выглядит более аккуратно и коротко, уже повод использовать
▫️ Может использоваться в заполнении лейаута, когда нам не нужно никакое другое взаимодействие с виджетом и поэтому сохранять его в переменную не требуется. Например, лейбл или кнопка.
widget = QWidget(minimumWidth=400)
layout = QHBoxLayout(widget)
layout.addWidget(QLabel("Button >", alignment=Qt.AlignRight))
layout.addWidget(QPushButton("Click Me", clicked=lambda: print("Button clicked")))
widget.show()
Либо так
widget = QWidget(minimumWidth=400)
layout = QHBoxLayout(widget)
for wd in (
QLabel("Button >", alignment=Qt.AlignRight),
QPushButton("Click Me", clicked=lambda: ...)
):
layout.addWidget(wd)
widget.show()
▫️ Можно хранить настройки в каком-то конфиге или генерировать на лету, после чего передавать как kwargs.
kwargs = {"text": "Hello " * 30, "wordWrap": True}
my_label = QLabel(**kwargs)
Как получить полный список доступных свойств?
Эта функция распечатает в терминал все свойства виджета и их текущие значения
def print_widget_properties(widget):
meta_object = widget.metaObject()
for i in range(meta_object.propertyCount()):
property_ = meta_object.property(i)
property_name = property_.name()
property_value = property_.read(widget)
print(f"{property_name}: {property_value}")
#tricks#qt
🏆🙌
🍀❤️🥰⚠️💥🛒
🎊🏷️🪢✏️
Si tu respuesta es SÍ, ÚNETE a este grupo
https://t.me/craftingtools que mañana damos inicio a diciembre con esta
✏️
✏️
✏️
✏️
🍀🙌🎰🎰🎰
🏆 1 Premio por valor superior a 40 MLC:
💙Set de cortadores de acero inoxidable
💙Set de mini cúter
💙4 cortadores de flor con sistema de expulsión
💙3 cortadores de estrellas
💙3 cortadores (oso, corazón y rosa)
💙200 cascabeles
💙Molde de silicona
💙100 Bases para aretes y 100 cierres de acero inoxidable
💙Set de 11 felpitas
💙1 tira de figuras de fomi
🏆🙌
🍀❤️🥰⚠️💥🛒
🎊🏷️🖇️🧿
#grupos
‼️ Atención‼️
NUEVA 🅞🅕🅔🅡🅣🅐 de compra, esta vez en 𝐀𝐧𝐢𝐦𝐚𝐥𝐞𝐬 𝐒𝐚𝐥𝐮𝐝𝐚𝐛𝐥𝐞𝐬, para los peludos de casa, escamosos y plumíferos también 🐶🐱🐹🐟🦜
Compras por encargo del catálogo SheIn. Use este enlace para unirse👇
https://t.me/animalessaludables
https://chat.whatsapp.com/DQf3jDayREZFmsgQe5fvJZ
#grupos
¿Que puede hacer este bot?
@GroupsMusicBot
Este bot te permite reproducir música en tus grupos a través de los nuevos chats de voz introducidos recientemente por Telegram.
¡Simplemente agregue el bot en su grupo y lea la lista de comandos para descubrir cómo usarlo!
Idioma: inglés
(Visto en @botsgram_cu)
#música#grupos
¿Que puede hacer este bot?
@GooofyBot
Este bot elimina todas las fotos de desnudos para que Telegram no prohíba tus grupos.
Idiomas: inglés árabe
(Visto en @botsgram_cu)
#grupos#herramientas
¿Que puede hacer este bot?
@famigliacounterbot
Family Counter es el bot que puedes usar para contar los mensajes de tu grupo y competir con otros.
¡Agrégalo a tu grupo para que entre en acción de inmediato!
Idioma: italiano
(Visto en @botsgram_cu)
#grupos#herramientas
¿Que puede hacer este bot?
@matanet_bot
Bot para cualquier chat. Elimina mensajes que contienen obscenidades, dejando un mensaje en el chat en el que educadamente pide no jurar.
Agrega el bot a tu chat y dale permiso para eliminar mensajes. No se requieren ajustes adicionales.
Idioma: ruso
(Visto en @botsgram_cu)
#herramientas#grupos
Como cada miércoles... Llega un
👆This or That👇
Este no es la excepción y viene con una sorpresa 😍👉entérate de los detalles aquí 👈 y únete a nuestro canal de importaciones 🛍️Accesorios BiA con ropita bonita🛒
#grupos#encuesta#bia_recomienda
¿Que puede hacer este bot?
@asamsgbot
Este bot le permite enviar mensajes privados en chats públicos, los mensajes solo son visibles para el destinatario y el remitente.
Sólo funciona de forma inline.
Idiomas: español, inglés, italiano
(Visto en @botsgram_cu)
#mensajes#grupos
¿Que puede hacer este bot?
@ThankStickerBot
Envía una calcomanía de agradecimiento al grupo cuando alcanza "x" cantidad de miembros.
Idioma: inglés
(Visto en @botsgram_cu)
#stickers#grupos
¿Que puede hacer este bot?
@KattoRobot
Bot de entretenimiento para grupos con comandos, tablas de clasificación y un sistema de puntos para mantener activo a tu grupo.
Idiomas: italiano
(Visto en @botsgram_cu)
#entretenimiento#grupos
¿Que puede hacer este bot?
@Membership_admin_bot
Este bot te ayudará a monetizar tus grupos de telegram, crear grupos privados pagados y vender productos
💵 Puede aceptar pagos
📆 Crear suscripciones
🌐 Dale a tus clientes enlaces de invitación
📌 Enviar recordatorios
⛔️ Prohibir a los que no pagan
🛍Vender Productos
Idioma inglés
(Visto en @botsgram_cu)
#membresía#grupos
¿Que puede hacer este bot?
@FeaturesBugsBot
Este bot le permite enviar nuevas Funciones e informar Errores de los usuarios del grupo. Los diversos informes se recibirán en un canal de registro.
Idiomas: inglés, español, italiano, indonesio, árabe
(Visto en @botsgram_cu)
#herramientas#grupos#canales