TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #381 · 23 окт.

Установить свойства виджета в 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

Hashtags

Резултати

Пронајдени 2 слични објави

Пребарај: #ogcommunity

当前筛选 #ogcommunity清除筛选
MoonPlay

@moonplay_official · Post #40 · 24.06.2024 г., 18:59

New Partnership Announcement: MoonPlay x OGCommunity!🚀 Hey Space Cadets! Kick-starting this week with the announcement of our partnership with👾OGCommunity - a powerhouse in the gaming industry with over 2 million members. They have something for everyone: communication with like-minded people, learning something new, earning money, investing, influencing the development of the industry, developing and launching projects in gaming, taking part in eSports tournaments, and playing the most exciting games. Together, we’re set to elevate your gaming experience to cosmic heights! 🔝 What This PartnershipMeans for You: 👥Enhanced Community: Benefit from the expertise and influence of one of the most impactful communities in gaming. 💸New Opportunities: Discover unique ways to earn, invest, and play, brought to you by the combined efforts of MoonPlay and OGCommunity. ✅Industry Influence: Be part of a movement that shapes the future of gaming, supported by a robust ecosystem of projects and initiatives. Together with OGCommunity, we’re bringing more excitement, innovation, and opportunities to your space adventures. Stay tuned for more updates 👀 as we embark on this stellar journey together! Stellar adventures start here:@moon_land_bot🚀 JOIN OGCOMMUNITY: ✉Channel ❌Twitter 🤖Discord *⃣Linktr.ee🐝Blog🐝OGC App #ToTheMoon#OGCommunity#MoonPlay#partnership#ecosystem#blockchain#gamefi#web3#wenlisting#airdropsoon#communityfirst#taptap#clicker#game

MoonPlay

@moonplay_official · Post #67 · 16.07.2024 г., 17:33

New Mission Pack Alert 👀 OGCommunity, known for building the most influential community and ecosystem in the gaming industry, brings you a fresh pack of missions! Connect with over 2 million members 👥, gain new knowledge, and take part in epic gaming experiences. 👉 Head right to Missions tab and complete special tasks curated by OGCommunity to earn rewards. Don't miss out on this opportunity. Together, we’ll conquer the cosmos and build a thriving lunar colony! 🤩 👉Start your To The Moon adventure now!👈 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#OGCommunity#ecosystem#blockchain#gamefi#web3#wenlisting#squad#mission#communityfirst#taptap#clicker#game