Регулярно приходится писать и ревьюить код, где используется 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
【#Yunxiao Sports】https://yunxiao61.vip(reputation disk)🥰
(reputation disk)🥰
😀😀😀😀😀
😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀
🤭No IP limit (you can deposit and withdraw via U for the first time)🥰
🤭"Zero review and worry-free for large amounts"
🤭The world's most prestigious betting market from Europe! The platform supports USDT, GOpay, OKpay, EBpay, WeChat, Alipay, virtual currency and other payment deposits and withdrawals👉 (1:1 for member EB sales)
🤭Open an account and get free gifts ✅#Limited time event: first deposit 300 will get you 178. If you deposit 500, you will get 288.
🤭Large customers with a single deposit of 1 million (no need to worry about making large withdrawals). Financial analysts are welcome to compete in Dog Village ❗️
🤭Important things to say twice: Withdraw money in seconds without stuck money Withdraw money in seconds without stuck money❗️
⚡️⚡️⚡️⚡️⚡️⚡️
⚡️⚡️⚡️⚡️⚡️⚡️⚡️
🤭The daily deposit bonus for the first deposit will not stop, 2% will be given for daily deposit, and more will be given on weekends. There are also monthly cash rebates, etc.
🤭If you meet the deposit requirement of 200,000 within 30 days of registration, you will receive a young model or the latest Apple mobile phone.
🌐Yunxiao Sports:https://yunxiao61.vip
🌐Event Specialist: @qiuxiaomi9876🥰
🤤😪😮💨😵😛😝😜🤪🤨🧐🤓😎🥸
🤭e-sports sports agreement to stabilize channels👉✈️@dianjingtuijian01
【#Yunxiao Sports】https://yunxiao61.vip(reputation disk)
🥰
(reputation disk)
🥰
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
😀
🤭No IP limit (you can deposit and withdraw via U for the first time)
🥰
🤭"Zero review and worry-free for large amounts"
🤭The world's most prestigious betting market from Europe! The platform supports USDT, GOpay, OKpay, EBpay, WeChat, Alipay, virtual currency and other payment deposits and withdrawals👉 (1:1 for member EB sales)
🤭Open an account and get free gifts ✅#Limited time event: first deposit 300 will get you 178. If you deposit 500, you will get 288.
🤭Large customers with a single deposit of 1 million (no need to worry about making large withdrawals). Financial analysts are welcome to compete in Dog Village ❗️
🤭Important things to say twice: Withdraw money in seconds without stuck money Withdraw money in seconds without stuck money❗️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
⚡️
🤭The daily deposit bonus for the first deposit will not stop, 2% will be given for daily deposit, and more will be given on weekends. There are also monthly cash rebates, etc.
🤭If you meet the deposit requirement of 200,000 within 30 days of registration, you will receive a young model or the latest Apple mobile phone.
🌐Yunxiao Sports:https://yunxiao61.vip
🌐Event Specialist: @qiuxiaomi9876🥰
🤤
😪
😮💨
😵
😛
😝
😜
🤪
🤨
🧐
🤓
😎
🥸
🤭e-sports sports agreement to stabilize channels👉✈️@dianjingtuijian01
Друзья, представляем нож Colada, выпущенный ограниченным тиражом.
Colada – это компактный нож-универсал, один из самых популярных в линейке Kizlyar Supreme. Простота, красота, завершенность - и ничего лишнего. Клинок классической формы выполнен из культовой немецкой стали PGK, а рукоять - из прочного черного композита.
Сталь PGK на клинке закалена до твердости 62-63 HRC - нож отлично держит заточку и обладает потрясающим резом. Обычно при такой твердости клинки становятся хрупкими, но только не из стали PGK!
Если вы хотите совместить:
🔪 отличный рез,
👌 удержание заточки
🗿 и высочайшую прочность,
смело выбирайте клинок из PGK.
Рукоять с выраженной шероховатой фактурой выполнена из черного G10. Нож комплектуется красивыми и удобными погружными кожаными ножнами с петлей свободного подвеса.
Купить в официальном интернет-магазине◀️
#Colada#Limited#PGK