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 слични објави

Пребарај: #carauction

当前筛选 #carauction清除筛选
Auto Life

@revheadcrypto · Post #518 · 23.09.2024 г., 20:54

🚗✨Rare Gem Alert: 1935 Mercedes-Benz 500K!✨🚗 A stunning piece of automotive history is hitting the auction block for $4-6 million! 💰🔥 This exquisite Mercedes-Benz 500K was built for the legendary pre-war racer Rudolf "Regensmeister" Caracciola. 🏁🏆 Its unique body was custom-designed to accommodate the tall stature of the champion driver! In 1979, the car found its way to Rudi Klein, who took it for a couple of events before locking it away in his barn, preserving its beauty for decades. 🏡🔒 #MercedesBenz500K#ClassicCars#CarAuction#RacingLegend#Auto

Auto Life

@revheadcrypto · Post #299 · 11.08.2024 г., 11:53

🚗✨ Rare Mercedes-Benz S-Class Coupe Up for Auction! ✨🚗 Check out this stunning 1980s Mercedes-Benz 500SEC, expertly tuned by AMG before it became part of the larger automotive group! 🏎️💨 🔧 Specs: - Original 5.0L V8 upgraded to a powerful 6.0L! 🔥 - Output increased to an impressive 330 HP! 💪 - Features include AMG springs, four-piston brake calipers, and stunning 17-inch OZ Racing wheels. 🛞 - Aerodynamic body kit for that sleek look! 🌬️ Don’t miss your chance to own a piece of automotive history! 🏆 #MercedesBenz#AMG#ClassicCars#CarAuction#SClass#Auto

Auto Life

@revheadcrypto · Post #227 · 03.08.2024 г., 08:02

🚗✨ Rare Pre-War Delahaye 135M Roadster Up for Sale! ✨🚗 This stunning automobile, crafted by the renowned Figoni et Falaschi atelier, is one of only 11 ever made in 1938, with fewer than five surviving to this day! 🌟 Originally ordered by an Algerian businessman in March 1938, its journey remains a mystery until the early 1990s when it was rediscovered in a garage by a French enthusiast. 🕵️‍♂️🔍 Since 1999, this exquisite piece of French automotive history has been owned by renowned American collector Robert Petersen and is periodically showcased in his museum. 🎨🏛️ Now, it's hitting the auction block with a price tag of $3 million! 💰💎 #Delahaye#ClassicCars#CarAuction#VintageAutomobile#FigoniEtFalaschi#LuxuryCars#CarCollector#AutomotiveHistory#RareFinds

Auto Life

@revheadcrypto · Post #343 · 19.08.2024 г., 20:06

🚗✨ Incredible Auction Alert! ✨🚗 Get ready for the chance to own a piece of racing history! 🏁 The legendary Mercedes-Benz W196 Streamliner is set to hit the auction block! 🎉 This extraordinary car, originally driven by the great Juan Manuel Fangio in a non-championship Formula 1 race in 1954, features the iconic streamlined body that has been preserved to this day. 🏆💨 Later, the car was driven by Stirling Moss during the 1955 Italian Grand Prix at Monza, where he recorded an impressive lap time before sadly retiring from the race. ⏱️🇮🇹 Auction estimates place this racing masterpiece at a staggering $50 to $70 million (approx. **₽4.7 to ₽6.3 billion**)! 💰💎 #MercedesBenz#W196#Streamliner#F1History#JuanManuelFangio#StirlingMoss#CarAuction#RacingLegend#LuxuryCars#Auto

Auto Life

@revheadcrypto · Post #492 · 15.09.2024 г., 15:36

🚗✨For Sale: A Rare Jaguar Duo!✨🚗 Up for auction on Pistonheads, we present a unique lot featuring two legendary Jaguars: the racing beast XJR-15 and the classic coupe XJR-S! 🏁 🌟Jaguar XJR-15🌟 - The world’s first production car with a carbon fiber body! 🏆 - Only 53 units produced from 1990 to 1992, all equipped with a powerful 6.0L V12 engine (450 hp). 🔥 - Out of those, only 27 are road-legal! This one is a pure track version with chassis number 48. 🏎️💨 - Notably, it won a support race for Formula 1 at Silverstone in 1991, driven by the legendary Juan Manuel Fangio II, with his autograph still gracing the body! ✍️🏅 #Jaguar#XJR15#XJRS#ClassicCars#CarAuction#Pistonheads#Motorsport#CarCollectors#RareCars#Auto🚘💖