Регулярно приходится писать и ревьюить код, где используется 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
swap.coffee: Halloween Event Wrap-Up
#DeFi#swap
The channel swap.coffee successfully concluded its Halloween Event with great participation and strong on-chain activity, turning it into a dynamic DeFi experience. Prizes for participants have already been distributed as per the winner list.
Source: link
@tonlines
Самым лёгким телефоном с сенсорным дисплеем по версии Книги Рекордов Гиннесса является вот этот малыш - sWaP Nova. Вес гаджета всего 40,3 грамма. Но, со своими функциями он вполне справляется – используя sWaP Nova можно звонить и отправлять SMS.
Многим он, конечно же, наверное и не знаком, но в Книге Рекордов он засветился 💪
Завтра расскажу про самый тонкий смартфон в мире по версии Книги Рекордов Гиннеса.
Ваши предположения, это.. ?? ))
#sWaP
#телефоны_рекордсмены
⚡️swap.coffee: $LAMBO Trading Competition Announcement
#LAMBO#swap
swap.coffee presents an exciting $LAMBO trading competition with a prize pool of $2,500. Participants can trade on swap.coffee or @swapi between November 19 and 21. Top traders and random participants have chances to win various prizes in $LAMBO and Lunar Snake Onyx Black gifts.
Source: link
@tonlines
swap.coffee: Results from Trading Competition with TONCO
#TONCO#swap
swap.coffee announces the conclusion of the Trading Competition with a total swap volume reaching $17,832,164. Rewards are now available for participants, including special prizes for 10 random users with significant swap contributions. Full details and participant lists are accessible through their provided link.
Source: link
@tonlines
⚡️swap.coffee: Exciting TONCO Trading Competition
#swap#TONCO
The swap.coffee channel has launched a trading competition in collaboration with TONCO, a pioneering DEX platform on TON. Participants can win rewards by trading through TONCO on swap.coffee, with opportunities to earn Vintage Sigare Telegram gifts and a share of $2,000 USDT. The competition runs until May 28.
Source: link
@tonlines
⚡️swap.coffee: Impressive April 2025 Metrics
#swap#metrics
Swap.coffee shared its growth metrics for April 2025, showing a transaction volume of nearly $18 million, 37,129 transactions, and 5,934 unique users. The team expresses gratitude for the ongoing support from their community.
Source: link
@tonlines
🆕New Mission is Live!
Make a swap and complete the basic security quiz to earn rewards! 🥇
➡️NFTs from the previous mission have already been sent.
➡️The streaks were added so you can track how many missions you've completed in a row.
Stay tuned for more updates in the Swap section coming soon! 😏
🔥Keep mining HOT!
#web3#hotwallet#swap#NFT
⚡️Swap.coffee: Instant Rewards and Staking Opportunities
#swap#staking#XROCK
Swap.coffee offers a unique and efficient staking experience, allowing users to claim their rewards instantly. Currently, a prize giveaway is available for staking $XROCK with friends from @XRocket. Tokens available for staking include CES, XROCK, JETTON, and DFC.
Source: link
@tonlines
⚡️swap.coffee: Torch Finance Integrated
#Torch#Finance#swap
swap.coffee has integrated Torch Finance as a new liquidity source. This integration enhances swap.coffee users' experience by providing optimized routes for trading liquid staking tokens, stablecoins, and yield-bearing tokens.
Source: link
@tonlines
⚡️Storm Trade x🏴☠️MyTonWallet: Trading Tournament with $2,500 Prize Pool!
Storm Trade Launches Joint Event with MyTonWallet — $2,500 in $STORM Tokens at Stake.
How to participate?
• Exchange $STORM in MyTonWallet
• Gain volume — it is automatically taken into account in the rating
• Get into the top 100 and get a share of $2,500 in $STORM
🗓Tournament dates: April 14 -- 29
💎Bonus from MyTonWallet: each participant of the contest will be credited with cashback in $MY. And when staking $MY the exchange fees are lower. 😉
🏆Follow the leaderboard, improve your positions and get your reward!
#Swap#Contest#MY#STORM