Установить свойства виджета в 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
🐈⬛NEW RELEASE
🐈⬛
🐈⬛Under Control Transforming Your Closed Guard by Brian Glick
🐈⬛
🐈⬛In Under Control: Transforming Your Closed Guard, Brian Glick delivers a complete system for building a closed guard that is tight, efficient, and relentlessly effective—regardless of size or strength
🐈⬛This is not a collection of random moves—it’s a carefully structured approach to controlling, breaking, and submitting opponents from one of jiu-jitsu’s most important positions.
$197
🐈⬛$14.99
🐈⬛
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#BrianGlick#Transitions#NoGi#NewWave
🐈⬛Buy
🐈⬛
😁See the Back Take The Back: Guard Passes To Back Takes by Giancarlo Bodoni😁
➡️See the Back, Take the Back: Guard Passes to Back Takes by Giancarlo Bodoni is the definitive blueprint for turning pressure passing into relentless back-taking offense.
➡️As a 2× ADCC champion, CJI standout, and one of the most technically disciplined athletes to emerge from the legendary Danaher system, Giancarlo has built his game around one thing: getting to the back and finishing—against everyone.
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#GiancarloBodoni#Transitions#NoGi#NewWave
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Take the Back from Closed Guard by Paul Schreiner😁
➡️Closed guard is one of the most powerful positions in Jiu-Jitsu — but many grapplers struggle to turn it into truly dominant finishes.
➡️Instead of relying only on sweeps or submissions, you’ll learn how to force reactions, break posture, and create openings that lead directly to back control — one of the most dominant positions in Brazilian Jiu-Jitsu.
$127😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#PaulSchreiner#Transitions#NoGi#IBJJF
💁♀️Buy
💁♀️
😁Jiu Jitsu For Old Guys: Entries For Over Under by Bernardo Faria😁
➡️Unlock the secrets to one of the most effective and accessible passing techniques in Brazilian Jiu-Jitsu with Jiu-Jitsu for Old Guys: Entries For Over Under by Bernardo Faria — 5x Black Belt World Champion, BJJ Fanatics Co-founder, and best-selling instructor.
➡️Designed specifically for older practitioners, this series emphasizes technique over athleticism, helping you maintain a competitive edge without relying on explosive power or speed
$197😍$19.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#BernardoFaria#Transitions#Gi#BjjFanatics
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Upper Lower Chains Links that Solve Problems Faster by Josh Saunders😁
➡️Unlock the secret to faster problem-solving and fluid movement on the mats with Upper Lower Chains Links that Solve Problems Faster, an innovative BJJ instructional by Josh Saunders — a 2x ADCC Trials winner and ADCC semifinalist.
➡️This groundbreaking approach empowers practitioners to adapt, innovate, and respond to challenges in real-time, making your game more dynamic and intuitive.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#JoshSaunders#Submissions#NoGi#Transitions
💁♀️Buy
💁♀️
😁Unpinable By Professor Henry Akins😁
➡️Henry shares the same principles passed down directly from Rickson Gracie—details rarely taught in modern academies—that turn crushing top pressure into an opportunity to escape, reset, and dominate the pace of the match.
➡️If you want a calm, technical escape system rooted in the deepest levels of Brazilian Jiu-Jitsu, Unpinable by Henry Akins will permanently change how you experience bottom position.
$279😍$24.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#HenryAkins#Transitions#NoGi#RicksonGracie
💁♀️Buy
💁♀️
😁Learning How To Relax In Jiu-Jitsu By Professor Henry Akins😁
➡️In Learning How to Relax in Jiu-Jitsu, legendary instructor Henry Akins reveals a groundbreaking approach to relaxation that transforms how you move, breathe, and apply technique on the mat.
➡️This course teaches you how to replace tension, panic, and wasted movement with structured breathing, intelligent pressure, precise timing, and effortless control
$279😍$24.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#HenryAkins#Transitions#NoGi#RicksonGracie
💁♀️Buy
💁♀️