TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #381 · 23 окт.

Установить свойства виджета в PySide можно не только через соответствующие методы и конструктор класса. Можно их изменять с помощью метода setProperty по имени. btn = QPushButton("Click Me") btn.setProperty("flat", True) Это аналогично вызову btn.setFlat(True) Если указать несуществующее свойство, то оно просто создается btn.setProperty("btnType", "super") Получить его значение можно методом .property(name) btn_type = btn.property("btnType") Когда это может быть полезно? ▫️Можно просто хранить какие то данные в виджете и потом их доставать обратно widget = QWidget() widget.setProperty('my_data', 123) print(widget.property('my_data')) ▫️ Назначая эти свойства разным виджетам можно потом отличить виджеты во время итераци по ним. Например, найти все кнопки со свойством my_data="superbtn". Но ведь вместо кастомного свойства можно использовать objectName, будет тот же результат. Да, но y ObjectName есть ограничение - только строки. ▫️ Если нам потребуется не просто поиск а, например, сортировка по числу, то свойства позволяют нам это сделать. Поддерживается любой тип данных widget.setProperty('my_data', {'Key': 'value'}) widget.setProperty('order', 1) all_widgets.sort(key=w: w.property('order')) Но ведь Python позволяет всё вышеперечисленное сделать простым созданием атрибута у объекта widget.order = 1 widget.my_data = 123 Да, но я думаю что не надо объяснять почему не стоит так делать. К тому же, если у виджета нет свойства то метод .property(name) вернет None, а отсутствующий атрибут выбросит исключение. ▫️ Действительно полезное применение кастомным свойствам - контроль стилей. Здесь атрибутами не обойтись, нужны именно свойства. Дело в том, что в селекторах стилей можно указывать конкретные свойства виджетов на которые следует назначать стиль. Просто запустите этот код from PySide2.QtWidgets import * if __name__ == "__main__": app = QApplication([]) widget = QWidget(minimumWidth=300) layout = QVBoxLayout(widget) btn1 = QPushButton("Action 1") btn2 = QPushButton("Action 2") btn3 = QPushButton("Action 3", flat=True) layout.addWidget(btn1) layout.addWidget(btn2) layout.addWidget(btn3) # добавим кастомное свойство одной кнопке btn1.setProperty("btnType", "super") # добавляем стили widget.setStyleSheet( """ QPushButton[btnType="super"] { background-color: yellow; color: red; } QPushButton[flat="true"] { color: yellow; } """ ) widget.show() app.exec_() С помощью селектора мы избирательно назначили стили на конкретные кнопки. Как получить список всех кастомный свойств? Функция получения списка кастомных свойств отличается от получения дефолтных. def print_widget_dyn_properties(widget): for prop_name in widget.dynamicPropertyNames(): property_name = prop_name.data().decode() property_value = widget.property(property_name) print(f"{property_name}: {property_value}") #tricks#qt

Hashtags

Резултати

Пронајдени 64 слични објави

Пребарај: #grupos

当前筛选 #grupos清除筛选
BiA Cerámica Fría

@biaceramicafria · Post #3856 · 30.11.2022 г., 17:34

🏆🙌 🍀❤️🥰⚠️💥🛒 🎊🏷️🪢✏️ 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

Hashtags

BiA Cerámica Fría

@biaceramicafria · Post #3621 · 20.06.2022 г., 13:50

‼️ 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

Hashtags

BotsGram®

@botsgram_cu · Post #3626 · 11.03.2021 г., 00:53

¿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

BotsGram®

@botsgram_cu · Post #4143 · 25.07.2021 г., 18:14

¿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

BotsGram®

@botsgram_cu · Post #3686 · 19.03.2021 г., 01:40

¿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

BotsGram®

@botsgram_cu · Post #3107 · 02.11.2020 г., 19:01

¿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

BiA Cerámica Fría

@biaceramicafria · Post #3662 · 20.07.2022 г., 16:28

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

BotsGram®

@botsgram_cu · Post #4026 · 17.06.2021 г., 02:28

¿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

BotsGram®

@botsgram_cu · Post #3609 · 09.03.2021 г., 12:46

¿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

BotsGram®

@botsgram_cu · Post #4179 · 09.08.2021 г., 15:43

¿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

BotsGram®

@botsgram_cu · Post #3088 · 27.10.2020 г., 01:55

¿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

BotsGram®

@botsgram_cu · Post #3860 · 30.04.2021 г., 23:25

¿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

123•••56
ПретходнаСтраница 1 од 6Следна