Установить свойства виджета в 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
⚡️Gatto Official Channel: PvP Event with Rewards
#GTON#PvP
Join the Gatto Official Channel for an exciting PvP event and fight against the GTeam from 15:00 UTC today. Players can earn special rewards by achieving consecutive wins against the GTeam, with the event running until May 30. European server only.
Source: link
@tonlines
MRKT: New Winter League Begins
#MRKT#PVP
The MRKT channel announces the start of the Winter Open League, bringing new competitions and rewards after the completion of the Autumn season. Players can look forward to fresh rankings, new rivals, and exclusive prizes including the Heart Locket and Durov’s Cap.
Source: link
@tonlines
⚡️MRKT: Important Update on PVP Competition Rules
#MRKT#PVP
MRKT announces a new rule to ensure fair competition in PVP leaderboards. Contributions exceeding 92% of a game's pool will not influence tournament rankings. Participants are encouraged to play fairly.
Source: link
@tonlines
MRKT: New Feature Enhances PvP Experience
#MRKT#PvP
MRKT introduces PvP Reactions, allowing players to drop reactions during fights to enhance excitement and energy in battles. This feature aims to change the atmosphere of the arena.
Source: link
@tonlines
MRKT Enforces Fair Play in PvP Events
#MRKT#PvP
MRKT emphasizes fair play in all PvP events, actively monitoring for suspicious activities like volume boosting and artificial staking. Participants found engaging in abuse or manipulation risk being banned without explanation.
Source: link
@tonlines
⚡️MRKT: Last Hours of PvP Tournament Finale
#PvP#Tournament
The MRKT channel announces that there are only 9 hours left in the Autumn Open League PvP Tournament. Participants still have the chance to improve their standings with every fight, stake, and point.
Source: link
@tonlines
⚡️Gatto Official Channel: Weekend Tournament Rescheduled
#tournament#PvP
The Gatto Official Channel has announced the cancellation of the weekend tournament due to technical improvements in PvP mode. The event has been rescheduled to April 25, with double rewards offered for skipping. More details will be provided on the event day.
Source: link
@tonlines
⚔️FOMO Fighters Player Database is Live!
Looking for opponents for PvP battles in 🔥Fomo Fighters ?
Now it's easier than ever.
I’ve created ⚡Fomo Tools — a app that collects the entire player database in one place so you can quickly search and find fighters.
⚔️What you can do:
🟢Find any player instantly
🟢Search fighters for PvP battles
🟢Explore the growing Fomo Fighters community
No more endless scrolling or guessing usernames — just search and battle ⚔️
Try it here:
📣 @FomoTools
If you enjoy the tool, feel free to share it with other fighters and make the PvP scene even more active!
#fomo#fighters#FomoFighters#PvP#tools
Gatto Official Channel: Celebrating Two Years of Growth
#Gatto#PvP#BattlePass
Gatto Official Channel marks its second anniversary with numerous updates and improvements. Over the past year, the game has expanded its offerings with new PvP mechanics, a Battle Pass, and additional content, enriching the player's experience. As the community celebrates, special events and items are available, leading up to upcoming giveaways.
Source: link
@tonlines
✅Nueva actualización del juego Solitario de THNDRGAMES.
⚒️ Ahora están disponibles los duelos PvP y por supuesto el que gane va a ganar satoshis
👉Más info aquí:
https://www.thndr.games/post/duels
✅Actualice la app si ya la tiene, sinó descarga los juegos aquí: ⚡THNDRGAMES
#pvp#p2e#btcln#freebtc