Установить свойства виджета в 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
Одна из важнейших тем в моей жизни — изучение творчества и превращение его в искусство.
Одним из самых выразительных типов современного искусства я считаю музыкальные клипы. Их много в моем канале. Клипы — синтез музыки, ритма, стиля и визуального ряда, уместного или дикого, красивого или уродливого, раскрывающего и дополняющего музыку.
Вот свежий клип Дейва Мейерса — он известный режиссер, 20 лет делает клипы для западных суперзвезд.
В клипе Gorilla меня особенно впечатляет, как он подает рэп-культуру (уличную, со своими фишками, рифмует ее с костюмами, чисто изобразительными элементами, а как круто они едут по серпантину парковки). Кроме того, есть модная версия видео, его можно посмотреть на сайте, где с помощью нейросети Microsoft AI изображение каждый раз меняется.
#vishot#futureisnow
AI is not the future… it’s the present!🔥
With ChatGPT Bot you can:
✅ Ask anything in seconds
✅ Get smarter answers every time
✅ Boost your workflow instantly
🔥20,000 tokens FREE every day — no limits, no excuses.
Your personal AI assistant is already waiting for you 💎
➖➖➖➖🔻
🧠 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#AI#ChatGPT#NeuralHubAI#FutureIsNow
➖➖➖➖🔺
Завтра в 13:00 в филиале Hotel Branch учебного центра ADC состоится грандиозный ивент Speaking Club на тему "Technology"! 🚀
🔌 Ваш гид в мир технологий — учитель Shukhrat, который поделится самыми горячими новинками и трендами. Не пропустите эту уникальную возможность прокачать свои навыки общения и узнать больше о будущем! 🌟
#ADCTechClub#SpeakingClub#FutureIsNow#УчимсяВместе
Если у вас есть какие-либо вопросы, не стесняйтесь обращаться к нам по телефонам:
📞 +998742261078 | +998742281121
или пишите в Telegram: @admofadc
Telegram|Instagram
🤖 OpenAI’s NextGenAI is Here to Supercharge Research & Education!
Big news, folks! OpenAI just launched NextGenAI, a game-changing consortium with 15 top-notch institutions like Harvard, MIT, and Oxford! They’re tossing in $50 million (yes, MILLION!) plus API access to turbocharge AI research and education.
🧠 What’s the vibe? Scientists hunting cures, students mastering AI, and scholars digging up epic insights – all with OpenAI’s tech in their toolbox!
💡 Picture this: Harvard speeding up rare disease diagnoses, Oxford digitizing ancient texts, and more. It’s like giving the world’s brainiest minds an AI-powered jetpack!
Stay tuned – this is just the start of something huge!
➖➖➖➖🔻
💎@Chatgpt_OfficialNews – Stay Updated! ⚡️
🧠 BOT: @Chatgpt_OfficialBOT
#️⃣#NextGenAI#AIResearch#EducationRevolution#OpenAI#FutureIsNow
➖➖➖➖🔺
☀️ Windows that generate electricity!
Scientists from The Hong Kong Polytechnic University (PolyU) have developed a new generation of transparent solar panels with a record efficiency of 6.05% — the highest ever achieved for semi-transparent photovoltaic cells.
💡 Unlike conventional solar panels, these elements remain transparent or slightly tinted, making them ideal for use as windows, facades, or even screens — without sacrificing natural light or architectural design.
🔋 The new panels are made from triple-junction materials, which provide:
• improved thermal insulation,
• high stability and durability,
• eco-friendliness and low production cost.
🏙️ In the future, such “solar windows” could become part of energy-generating buildings capable of powering themselves, reducing strain on urban power grids, and lowering carbon footprints.
#technology#science#solarenergy#PolyU#innovation#futureisnow
🚀 ICT WEEK UZBEKISTAN 2026
The future isn’t coming.
It’s being built — right here, right now.
This September, Tashkent becomes the meeting point of global innovation. Visionary leaders, fast-growing startups, top tech companies, policymakers, and international partners will gather to shape the next era of digital transformation in Central Asia and beyond.
🌍 Discover breakthrough technologies
🤝 Meet decision-makers and global partners
💡 Turn bold ideas into real projects
📈 Unlock new markets and opportunities
This is not just an event.
Whether you are a government leader, investor, entrepreneur, tech professional, or innovator —
ICT Week Uzbekistan is where you need to be.
✨ Why attend?
✔️ High-level networking with global tech leaders
✔️ Startup & innovation showcases
✔️ Strategic forums and policy dialogues
✔️ Investment and partnership opportunities
✔️ Access to the fast-growing Central Asian tech market
📍 Tashkent, Uzbekistan
📅 September 22–25, 2026
Be part of the conversations that will define your tomorrow.
Join ICT Week Uzbekistan 2026.
Let’s connect. Let’s collaborate. Let’s build the future — together.
#ICTWeekUzbekistan2026#ICTWeek#DigitalTransformation#Innovation#TechLeadership#CentralAsia#FutureIsNow#Uzbekistan
🚀 ICT WEEK UZBEKISTAN 2026
The future isn’t coming.
It’s being built — right here, right now.
This September, Tashkent becomes the meeting point of global innovation. Visionary leaders, fast-growing startups, top tech companies, policymakers, and international partners will gather to shape the next era of digital transformation in Central Asia and beyond.
🌍 Discover breakthrough technologies
🤝 Meet decision-makers and global partners
💡 Turn bold ideas into real projects
📈 Unlock new markets and opportunities
This is not just an event.
Whether you are a government leader, investor, entrepreneur, tech professional, or innovator —
ICT Week Uzbekistan is where you need to be.
✨ Why attend?
✔️ High-level networking with global tech leaders
✔️ Startup & innovation showcases
✔️ Strategic forums and policy dialogues
✔️ Investment and partnership opportunities
✔️ Access to the fast-growing Central Asian tech market
📍 Tashkent, Uzbekistan
📅 September 22–25, 2026
Be part of the conversations that will define your tomorrow.
Join ICT Week Uzbekistan 2026.
Let’s connect. Let’s collaborate. Let’s build the future — together.
#ICTWeekUzbekistan2026#ICTWeek#DigitalTransformation#Innovation#TechLeadership#CentralAsia#FutureIsNow#Uzbekistan
🎬ПРЕМЬЕРА ГОДА: КОНЕЦ ЭПОХИ ИНСТРУКЦИЙ
Мир изменился. Искусственный интеллект больше не фантастика, это наш конкурент. Или наш инструмент?
9 января команда Mezon Inspiring School уходит в Deep Work на Ретрите.
Мы закрываем двери, чтобы открыть новую реальность. Реальность, где:
❌ Учитель больше не дает готовых ответов. ❌ Ученик больше не ждет инструкций.
❌ Родитель больше не делает домашку.
НАША ЦЕЛЬ — КОГНИТИВНЫЙ СУВЕРЕНИТЕТ. Мы проектируем школу, где выращивают не «удобных детей», а Субъектов — авторов своей жизни. Тех, кто сможет сказать ИИ: «Я здесь главный».
4 Команды.
3 Сессии.
1 Фундаментальный сдвиг.
Ты готов к Будущему?
#MezonSchool#Education2026#FutureSkills#AIvsHuman#Agency#Subjectivity#TashkentEducation#Blockbuster#MezonRetreat#Subjectivity#AI_Education#FutureIsNow
#Новаяшкола#NewSchool