Регулярно приходится писать и ревьюить код, где используется 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
⚽️🇪🇺Champions
Atalanta 0-0 Arsenal#Champions#Atalanta#Arsenal
El Arsenal no había conseguido marcar en sus últimas tres visitas a Italia... y volvió a olvidarse el 'cañón' en Londres. Esta vez, al menos, terminaron rascando un empate (0-0) gracias a un heroico David Raya que le detuvo un penalti a Retegui... y firmó una de las paradas del año en el rechace para terminar salvando los muebles.
https://www.marca.com/futbol/champions-league/cronica/2024/09/19/66ec5e6822601d4f558b45c4.html
Otros marcadores
Estrella Roja 1-2 Benfica
Feyenoord 0-4 Leverkusen
Brest 2-1 Sturm Graz
🏆@Info288_deportes
La Juventus le ganó con un único gol de Vlahovic al Atalanta en la final de la Copa Italia y llegaron a 20 títulos de Copa
@Fut_planet⚜️#CopaItalia🇮🇹#Juventus🇮🇹#Atalanta🇮🇹
#EU naval forces take control of hijacked #Iranian vessel off #Somalia
EU naval forces under Operation #Atalanta have reported the liberation of the Iranian-flagged dhow Alwaseemi, which was hijacked 400 nautical miles East of #Mogadishu last March 24.
"The pirates left the fishing vessel as a result of the pressure and presence exerted by Atalanta assets, in close coordination with Somali maritime police forces," Operation Atalanta said on Monday, April 6.
On Sunday, April 5, Alwaseemi was liberated by Atalanta elements. The Iranian-flagged fishing vessel was finally abandoned by the unnamed pirate group on the northwestern coast of Somalia, after being pressured by ATALANTA assets.
"Always prioritising the safety of hostages, a smart combination of 'concertina effect' conducted by Atalanta surface and air assets, plus a close and permanent coordination with Somali maritime.....
https://www.bairdmaritime.com/security/incidents/piracy/eu-naval-forces-take-control-of-hijacked-iranian-vessel-off-somalia
Por otra parte, en Europa League🟠 el día de hoy, también se decidirán los finalistas de la competición.
De un lado, Marsella🇫🇷 y Atalanta 🇮🇹 están empatados 1-1 en el global
Del otro lado, el Leverkusen🇩🇪 va ganando 2-0 en el global y quiere seguir haciendo historia, el conjunto de Xabi Alonso🇪🇸 se verá cara a cara contra los Romanos comandados por De Rossi🇮🇹
@Fut_planet⚜️#UEL🟠#Marsella🇫🇷
#Atalanta🇮🇹#Roma🇮🇹#Leverkusen🇩🇪
Italy Serie A🇮🇹
2026-04-06 10:30 UTC
Udinese vs. Como
Predicted outcome: Como❌
Predicted score: 1:2
Actual: Draw 0:0
#Udinese#Como
2026-04-06 13:00 UTC
Lecce vs. Atalanta
Predicted outcome: Atalanta✅
Predicted score: 0:1
Actual: Atalanta 0:3
#Lecce#Atalanta
2026-04-06 16:00 UTC
Juventus vs. Genoa
Predicted outcome: Juventus✅
Predicted score: 2:1
Actual: Juventus 2:0
#Juventus#Genoa
2026-04-06 18:45 UTC
Napoli vs. AC Milan
Predicted outcome: Draw❌
Predicted score: 1:1
Actual: Napoli 1:0
#Napoli#Milan
#Football#ItalySerieA
Italy Serie A🇮🇹
2026-03-22 11:30 UTC
Como vs. Pisa
Predicted outcome: Como✅
Predicted score: 2:1
Actual: Como 5:0
#Como#Pisa
2026-03-22 14:00 UTC
Atalanta vs. Hellas Verona
Predicted outcome: Atalanta✅
Predicted score: 2:1
Actual: Atalanta 1:0
#Atalanta#HellasVerona
🔥 PREMIUM PICK 🔥
2026-03-22 14:00 UTC
Bologna vs. Lazio
Predicted outcome: Draw❌
Predicted score: 1:1
Actual: Lazio 0:2
#Bologna#Lazio
2026-03-22 17:00 UTC
AS Roma vs. Lecce
Predicted outcome: AS Roma✅
Predicted score: 2:1
Actual: AS Roma 1:0
#Roma#Lecce
2026-03-22 19:45 UTC
Fiorentina vs. Inter
Predicted outcome: Inter❌
Predicted score: 1:2
Actual: Draw 1:1
#Fiorentina#Inter
#Football#ItalySerieA
Italy Serie A🇮🇹
2026-05-10 10:30 UTC
Hellas Verona vs. Como
Predicted outcome: Como✅
Predicted score: 0:1
Actual: Como 0:1
#HellasVerona#Como
2026-05-10 13:00 UTC
Fiorentina vs. Genoa
Predicted outcome: Genoa❌
Predicted score: 1:2
Actual: Draw 0:0
#Fiorentina#Genoa
2026-05-10 13:00 UTC
Cremonese vs. Pisa
Predicted outcome: Cremonese✅
Predicted score: 2:1
Actual: Cremonese 3:0
#Cremonese#Pisa
2026-05-10 16:00 UTC
Parma vs. AS Roma
Predicted outcome: AS Roma✅
Predicted score: 1:2
Actual: AS Roma 2:3
#Parma#Roma
2026-05-10 18:45 UTC
AC Milan vs. Atalanta
Predicted outcome: Atalanta✅
Predicted score: 1:2
Actual: Atalanta 2:3
#Milan#Atalanta
#Football#ItalySerieA