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

Резултати

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

Пребарај: #geography

当前筛选 #geography清除筛选
Language Trivia 🤔

@languagetrivia · Post #301 · 09.11.2024 г., 17:57

Gibraltar is a small territory located on the southern coast of the Iberian Peninsula, on the Mediterranean Sea. It is bordered by Spain to the north and sits at the entrance of the Strait of Gibraltar, which separates Europe from Africa. Known for its iconic Rock of Gibraltar, this territory has a unique geographic and cultural identity. What is the official language of Gibraltar? • A) Spanish • B) English • C) Andalusian Arabic • D) Portuguese Press ❤️ Follow @languagetrivia for more fun facts! #geography#guess_the_language

The Salzkammergut is a region in Austria, mostly frequented for relaxation vacation, hiking and climbimg. It stretches from the city of Salzburg eastwards to the Dachstein Mountains. The historic city of Hallstatt is located in the Salzkammergut, giving name to the Hallstatt culture, the predominant Western and Central European culture of the late Bronze Age from the 12th to 8th centuries BC and early Iron Age from the 8th to 6th centuries BC. #geography#history @EuropeanTribalism

Language Trivia 🤔

@languagetrivia · Post #123 · 04.10.2024 г., 17:20

What is one of the two official languages of Macau, a region of China often referred to as the 'Las Vegas of the East'? 🧠 Join @languagetrivia for more fascinating questions #guess_the_language#image#geography Check out the correct answer in the comment

Interesting Planet 🌍

@interesting_planet_facts · Post #1298 · 17.02.2026 г., 22:11

🌎 Along the India-Bangladesh border, a cluster of over 160 tiny enclaves once existed, creating a patchwork of territories within territories. Before a 2015 land swap, some villages belonged to India but were completely surrounded by Bangladesh, and vice versa, forming the world’s most complex international border tangle. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1202 · 07.01.2026 г., 22:11

🌎 Baarle-Hertog and Baarle-Nassau, two towns in Belgium and the Netherlands, form one of the world’s most complex borders, with 26 separate enclaves and counter-enclaves interlocking like a puzzle. Some houses are split between countries, with the nationality determined by the location of the front door. ✨ #geography⚡#borders⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1115 · 09.12.2025 г., 22:11

🌎 The border between India and Bangladesh features over 160 enclaves and counter-enclaves—small pockets of land belonging to one country inside the other. Before a 2015 land swap, Dahala Khagrabari was the world’s only third-order enclave: an Indian village inside a Bangladeshi enclave, within an Indian enclave, inside Bangladesh. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1083 · 29.11.2025 г., 12:11

🌎 Few borders are stranger than the Haskell Free Library and Opera House, built in 1904 directly on the US-Canada line. The building straddles Derby Line, Vermont, and Stanstead, Quebec, with a black line on the floor marking the international boundary. Its reading room is in the US, but most books are in Canada. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1051 · 18.11.2025 г., 22:11

🌎 Strange borders divide the island of Cyprus: the capital, Nicosia, is split by the "Green Line," a UN-controlled buffer zone between Greek and Turkish Cypriot sectors. This boundary cuts through streets and buildings, creating the world’s last divided capital city. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1012 · 07.11.2025 г., 12:11

🌎 The divided town of Baarle straddles the border between Belgium and the Netherlands in a tangled patchwork of enclaves. Some houses are split by the boundary, so front doors determine which country's laws apply. This border complexity results from medieval land deals, with 22 Belgian and 8 Dutch enclaves in total. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••6364
ПретходнаСтраница 1 од 64Следна