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

Резултати

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

Пребарај: #maqetuka

当前筛选 #maqetuka清除筛选

Farewell to Ambassador Mzuvukile Maqetuka 📅 March 31 marks the final day of the tenure of South African Ambassador to Russia and Belarus Mzuvukile Maqetuka. Today, he is departing from Russia. 💌 An excerpt from a farewell letter by the Honorary Consul of South Africa in Yekaterinburg, Sergey Mazurkevich, to Ambassador Maqetuka: "All our meetings have been truly memorable, and each time, you have emphasized the importance of fostering strong people-to-people ties. Your words have been a source of inspiration, guiding my efforts in this role. (...) Your Excellency, it has been an honor, privilege, and pleasure to know you personally and to serve as the Honorary Consul of South Africa under your leadership. My team and I remain committed to strengthening the ties between our nations, guided by the priorities you have set. Please accept our heartfelt gratitude, and our best wishes for your future endeavors." 🌍 Ambassador Maqetuka's dedication to building lasting connections and promoting cooperation between Russia and South Africa will be remembered and appreciated. Wishing him success in his future endeavors! #SouthAfrica#Russia#Diplomacy#Ambassador#InternationalRelations#Maqetuka#Mazurkevich

📚 At the international book festival Red Line, the Russian edition of Jim is Tired of Jo’burg by former South African Ambassador to Russia Mzuvukile Maqetuka was officially presented. 💬 In a lively dialogue, translator Dr. Dmitry Pobedash and editor Dr. Mikhail Brodsky explored the challenges of literary translation and shared fascinating stories about 🇿🇦 South Africa with the audience. 🤝 The event was made possible with the support of Ural Federal University Press and the Office of the Honorary Consul of South Africa in Yekaterinburg. #Culture#Literature#Festivals#SouthAfrica#Yekaterinburg#Translation#Maqetuka#Mazurkevich#UrFU

South Africa from A to Z: students, graduates, and professors of the Institute of International Relations (IIR) discovered many fascinating facts about the country! On March 22, South African English teacher Samora "Sam" Poswa held an engaging presentation at IIR, sharing insights about his homeland and answering numerous questions. The event was organized with the support of the Office of the Honorary Consul of South Africa in Yekaterinburg. The Office staff presented IIR Rector Dr. Irina Vylegzhanina with the Russian edition of Jim Is Tired of Jo’burg by South African Ambassador to Russia Mzuvukile Maqetuka, translated in 2024. They also spoke about the history of the project initiated by HC of South Africa Sergey Mazurkevich. #SouthAfrica#internationalrelations#education#culture#IIR#IMS#Maqetuka#Mazurkevich#Yekaterinburg

Во вторник 10 декабря Почётный консул Сергей Мазуркевич встретился в Москве с Послом ЮАР Мзувукиле Макетукой. Они обсудили текущие проекты офиса Почётного консула ЮАР и планы на 2025 год. #встречи#новости#Посол#Макетука#Мазуркевич _________________ On Tuesday, December 10, Honorary Consul Sergey Mazurkevich met with South African Ambassador Mzuvukile Maqetuka in Moscow. They discussed current projects of the Honorary Consul's office and plans for 2025. #meetings#news#Ambassador#Maqetuka#Mazurkevich

🇿🇦📖Jim may be tired of Jo’burg, but Yekaterinburg certainly isn’t tired of Jim! 📚 On August 22–24, the Red Line Book Festival (“Krasnaya Strokа”) — Yekaterinburg’s international book festival — will feature a new presentation of the Russian translation of Mzuvukile Maqetuka’s novel Jim Is Tired of Jo’burg. 📍The presentation format was discussed by representatives of the Office of the Honorary Consul of South Africa, translator Dr. Dmitry Pobedash (📸 right), and Dr. Aleksey Podchinyonov, the CEO of the Ural University Press (📸 left). 🗓 A year ago, an earlier presentation of translated chapters took place at the same festival: 🔗https://t.me/sarconsulurals/1340 📌 Details about the exact time and venue will be announced soon. #SouthAfrica#Yekaterinburg#Ural#RedLineFestival#Literature#AfricanLiterature#Translation#Maqetuka#UrFU#JimIsTiredOfJoburg