Установить свойства виджета в 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
🔥1 week after Dragon's Call release and we got:
👾70,000players played
😮x1268max win
In celebration of this we redesign game cover in different art styles🎨, try to guess what those styles are!
#dragonscall#truelab#slots
We give 50 USDT🤑to the first person who catches x100 or more at Guns, Love & Therapy.
Valentine's Day, 2123. The wrong time to be coming out, but not for our brave guys whose love can't be broken💜
Play on any platform, catch x100+, send a link to the replay and get 50 USDT to your wallet🤝
👉TRY GAME
#ValentinesDay#truelab#FreeMoney
❄️ Arctic Spin is Coming Soon! ❄️
We’re thrilled to announce Arctic Spin, our frosty new 3x3 slot, launching on the 14th November! With sleek winter visuals, variable paylines, and fast-paced gameplay, this game delivers a cool twist on classic slots. Get ready to spin through the snow and uncover some frozen treasures! ❄️🎰
⛄️ Stay tuned for updates!
#ArcticSpin#ComingSoon#TrueGames#TrueLab#TrueSlots
⚔️Battle Rage: new game — new UI
⚡️ Our yet to be released game Battle Rage will feature a completely revamped user interface! This is the first game to debut with our fresh, modern design — and trust us, it’s sleek, user-friendly, and visually stunning 🔥
🎮 Unlike many other providers, our new UI will offer a smooth and enjoyable top-notch experience, giving us a major edge in the gaming world.
💯 Not to mention that Battle Rage is set to be the hit of the year! Your favorite streamers will be playing it online, including the legendary Eddie from Stake. So, don't miss out! 💣
➡️ TRY DEMO NOW!
Coming very soon!
#BattleRage#newgame#comingsoon#TrueLab#TRUEGames
Get hooked on Fishy Business' Hold'n'Win respins! With every landed coin, your 3 respins reset, keeping the action alive and swimming! Complete all reel positions for a shot at the x1000 jackpot!
Ready to reel in the big one? Fishy Business launched on August 22nd! 🎰💦
Give it a go! https://bit.ly/fishy-business-demo
#FishyBusiness#HoldnWin#ComingSoon#TrueSlots#TrueGames#TrueLab
🔞 | Play Responsibly
Only 3 Days Until FRUIT CIRCUS PARTY! 🍉🎪
Why wait for the fun? The Buy Bonus feature lets you jump straight into the bonus round, where multiplicative multipliers never reset between spins. More spins, more multipliers, more mayhem! 🎢
Tick-tock, the madness begins in just 3 days. June 27th – mark the date!
➡️DEMO: https://bit.ly/demo-fcp
#FruitCircusParty#MultiplicativeMultipliers#BuyBonus#TrueLab#TrueGames#TrueSlots
Fishy Business is OUT NOW! 🐟💰
No more waiting—our top catch of the year has surfaced! Fishy Business delivers high volatility undersea action with 25 paylines, Hold'n'Win thrills, and a shot at x5000 max wins. The Bassline Bonanza Free Spins make this one dive you won’t want to miss, as reels 2, 3 and 4 convert into one huge symbol for some truly huge wins! 🌊⚡
Ready to take the plunge? 🤿
🎰 SPIN IT: https://bit.ly/fishy-business-demo
#FishyBusiness#OutNow#HoldnWin#TrueSlots#TrueGames#TrueLab
🔞 | Play Responsibly
The Wait is Over — Hot Devil Slot is Here! 😈
Kick off our HOT Series with a spin that’s hotter than your ex and easily twice as fun. Ready to play with fire or just here to warm up? With classic gameplay turned up to inferno levels, every spin is destined to thrill.
Let the games begin! 🔥
🍒 IGNITE THE FUN: https://play.truelab.games/game/hot-devil-slot-v1/static/index.html
#HotDevilSlot#OUTNOW#igamingnews#TrueLab#TrueSlots#TrueGames
🔞 | Play Responsibly
🎃 Happy Halloween, thrill-seekers! 🎃
Tonight’s the night to embrace the spooky spirit, and what better way than with Wild Pumpkins Deluxe? Our Halloween-themed slot is packed with sticky wilds, multipliers, and more ways to win than you can shake a broomstick at.
Forget the candy—tonight’s treat is big win potential! Brave enough to give it a spin?
Play Wild Pumpkins Deluxe and let the haunting begin! 👻
🎰GIVE IT A SPIN:https://bit.ly/wpd-demo
#HappyHalloween#WildPumpkinsDeluxe#TrickOrTreat#TrueLab#TrueGames
Step Right Up! Step right up! There's a new circus hitting town!
Tired of bland fruits? Us too. Meet FRUIT CIRCUS PARTY – where cascading wins, high volatility, and multipliers up to x10,000 make your average fruit game look like a snooze fest. 😴💣
Why? CASCADING MULTIPLICATIVE MULTIPLIERS, that's why. 🔥
We're talking 243 Ways to Win, Cascading multipliers and a bonus buy to get you right into the action.
This isn't your average circus. Launching 27th June. 🗓️
#CircusFruitParty#MultiplicativeMultipliers#BuyBonus#ComingSoon#TrueLab#TrueSlots#TrueLab
FRUIT CIRCUS PARTY brings fruit carnage to a whole new level! Step right up, there's a new circus in town! 🎪
Cascading wins unlock fresh combos & crank up the multipliers. Madness begins June 27th! 🗓️
➡️ DEMO: https://truelab.games/games/fruit-circus-party
#FruitCircusParty#CascadingWins#MultiplierChaos#TrueLab#TrueGames#TrueSlots
Only one week left until HOT MONEY hits the scene on June 13th!
Classic fun meets new age looks in the second game of our Hot Series. It's going to be a hot blast from the past, but better. 🔥
Demo Dropped! Check it: https://truelab.games/games/hot-money-slot
#HotMoney#AlmostHere#iGamingNews#TrueGames#TrueSlots#TrueLab