Установить свойства виджета в 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
The long-awaited listing of the token from Fanton Fantasy
🟨 We would like to remind you that #FTON is a utility token of the Fanton Fantasy project, necessary for playing in their tournaments. Token holders will be able to participate in betting and ⛏ farming, receive in-game bonuses, and also have the exclusive right to purchase NFT cards of the project.
↗️ The listing of $FTON will take place on October 1 at 13:00 UTC (16:00 Moscow time) on three CEX exchanges at once: Kucoin, Gate.io , MEXC. In our 🪙#TON network, the pool will appear at 13:15 UTC and unfortunately only on 1 DEX exchange – Ston.FI. At the same time, the team itself states that they are working with other sites on the token listing, so we are waiting for announcements.
➖After listing, life is just beginning, and we will begin to systematically increase the utility for $FTON, both for Fanton Fantasy players and ordinary cryptans!
The team also reminded us that Notcoin and Tonstarter are among their key partners:
➖Over the past 1.5 years, we in the Fanton team have held many calls with the creators of the best platform for social campaigns — Community, as well as Notcoin, which blew up TON and Telegram in early 2024.
➖Since then, we have been calling the guys weekly, maintaining a connection on the topic of launchpads and launching ⚽️ $FTON, received expertise and connections, and are finally close to launching our utility token.
Fanton | News | Chat | ChainGPT
Fanton EN: New Legendary NFTs and Staking 2.0
#NFT#FTON
Fanton EN presents the new Staking 2.0, featuring a convenient chart and distinguished Legendary NFTs, including players like Batrakov and Osipenko. The first round of NFT distributions for FTON stakeholders will start tomorrow. Participants can exchange injured NFTs through support.
Source: link
@tonlines
⚡️Fanton EN: Launch of Staking 2.0
#Fanton#FTON#NFT
Fanton EN channel has announced the launch of Staking 2.0 in the game, offering lucrative opportunities for players. By staking $FTON tokens, participants can earn rewards surpassing the token’s value and receive additional NFTs. Important deadline: Stake before April 19 to secure your NFT before the 25th RPL round.
Source: link
@tonlines
⚡️Fanton EN: Launch of Staking 2.0 with NFTs and Tournaments
#FANTON#NFT#FTON
Fanton EN introduces Staking 2.0, featuring NFTs, tournaments, and appealing bonuses. Participants can stake FTON in four different pools, each offering unique rewards like NFT cards, tournament entry, and up to 10% APY. The update includes guaranteed RPL NFTs and the opportunity to join exclusive pools with limited slots.
Source: link
@tonlines
⚡️Fanton EN: May Leaderboard Kicks Off with New Rewards
#FTON#NFT#RPL
Fanton EN has announced the results for April with $FTON and NFT card distributions to players. The May Leaderboard requires participants to earn at least 50 trophies to share a 1 million $FTON prize pool. Top players will also receive Rare RPL cards, selected based on rank.
Source: link
@tonlines
🏷 Start of presale from Fanton
🟡Placement will take place on August 7th at 11:00 UTC on the Magic Square platform
🟡Presale price – $0.023 (5% discount to the IDO price)
🟡Total raised amount – $150,000
🏆 We want to remind you that $FTON is a utility token for the Fanton Fantasy game, necessary for playing in project's tournaments. Token owners will be able to participate in staking and ⛏ farming, receive in-game bonuses, and also have exclusive right to purchase NFT cards of the project.
The first part of FCFS/Whitelist Round:
🟨Create an account on Magic Square and go through KYC
🟨Use wallet which completed the Zealy campaign
🟨Click "Join Whitelist"
Second part of the ProRata Round will begin on August 8th at 11:00 UTC.
📊 Allocation will depend on thr amount you contributed in relation to other participants. Trading with other users (until TGE) will appear on Magic Square OTC marketplace. More information in detailed guide - link here.
#fanton#magicsquare#fton