Регулярно приходится писать и ревьюить код, где используется 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
#Musical chair
Activity for review vocabulary
Class 7️⃣"Active"
Students learned vocabulary Time⏰
On each chair stuck the words from the topic time
When music🎶 plays students walking around the chairs and dance 🕺💃
When music pauses they should sit and say the word with its meaning
The challenge is that students' numbers are more than chairs. And also if students can not say the meaning they can not participate in the activity anymore
Aim of the activity
Review vocabulary
Enhance vocabulary ⬆️
Motivate students to learn foreign language
Relaxation 😂
Work on concentration🤔
Energizer😉
Learning should be
Easy and Enjoyable 😎👍
Teacher Umida Pulatova
Kushtepa district Specialized School
Fergana Region
https://t.me/LanguageStuff
🎬 Whiplash: Em Busca da Perfeição (2014)
Gênero: #Drama, #Musical
⭐️ IMDb: 8.5
⏳ Duração: 1 h 46 min
📝 Sinopse:
Um jovem e promissor baterista se matricula em um conservatório de música onde seus sonhos são guiados por um instrutor que não pára por nada para perceber o potencial de um aluno.
Fonte: IMDb
🔵Inscreva-se em @Assistir
*Patrocinado: Anime Bot
📺- CHICA VAMPIRO -📺
Título original: Chica Vampiro
Género:#Fantasía#Musical
Temporadas: 1
Año: 2013 📼
Origen: Colombia 🇨🇴
Tráiler:youtu.be/tlNRg_fYFU4
Sinopsis:
Daisy O'Brian es una chica normal que sueña con una carrera como cantante en comedia musical. Sus padres son vampiros y, según la tradición familiar, debe decidir convertirse en vampiro o no en su cumpleaños número 16. Ese día, Daisy decide seguir siendo humana para vivir junto a su amor, Max, que es su vecino y compañero de clase.
Disponible:Netflix | Vix | HBO Max
@SeriesClubHD
🍿 Lady Gaga and Joaquin Phoenix unleash chaos in 'Joker: Folie à Deux'
📆Premiere: October 4, 2024
🎭Genre: #Drama · #Musical
🎬 The first trailer for 'Joker: Folie à Deux' is here! Joaquin Phoenix returns as Arthur Fleck, joined by Lady Gaga as Harley Quinn. This dynamic duo promises chaos and music in a sequel that takes place mostly in Arkham Asylum. 🌆🃏
The first film was a massive hit, winning the Golden Lion and multiple Oscars, including Best Actor for Phoenix. This time, in addition to the usual madness, we'll see unique musical elements that will surprise everyone. Don't miss it! 🎤💥