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

Резултати

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

Пребарај: #gattoverse

当前筛选 #gattoverse清除筛选
TONlines – News

@tonlines · Post #7240 · 16.05.2025 г., 13:37

Gatto Official Channel: Weekend Tournament Begins #GattoVerse#TON The GattoVerse Weekend Tournament kicks off, offering players the chance to win extraordinary prizes, including TON and various resources. The tournament starts on May 16 and ends on May 19. Participants are encouraged to join PvP battles and climb the leaderboard to secure top spots. Source: link @tonlines

TONlines – News

@tonlines · Post #6757 · 14.04.2025 г., 14:29

⚡️Gatto Official Channel: Dive into the GattoVerse NFT Adventure! #GattoVerse#TON GattoVerse welcomes the legendary NFT collection The Doge Pound with a trading volume of over $50,000,000. Join the event "Who let the dogs out?" and obtain new pets by purchasing Diamond Paws, which will transform into unique collectibles in two weeks. Source: link @tonlines

TONlines – News

@tonlines · Post #7186 · 13.05.2025 г., 09:04

⚡️Gatto Channel: Exciting Rewards with Lord Diamondog #GTON#GattoVerse Lord Diamondog has brought silver coins for $GTON, allowing players to purchase them and receive special rewards from the Hat Mouse Shop. Key prizes include treasury gold, spells, and resources for the future Lords of the GattoVerse, with bonus advantages for premium ticket holders. Source: link @tonlines

TONlines – News

@tonlines · Post #7025 · 02.05.2025 г., 13:32

Gatto | Official Channel: Battle in the GattoVerse #GattoVerse#GTON Gatto | Official Channel announces an exciting Weekend Tournament in the GattoVerse. Participants can win marvelous gifts, including various eggs, gold coins, and exclusive Gattoboxes. The tournament starts today and ends on May 5, with a special raffle using Crocottery Tickets. Source: link @tonlines

TONlines – News

@tonlines · Post #7138 · 09.05.2025 г., 12:38

Gatto | Official Channel (18+): Weekend Tournament Details #GattoVerse#Tournament GattoVerse is hosting a high-stakes Weekend Tournament starting today and ending on May 12. Participants in the PvP battles for $GTON can win prizes, including gold coins and exclusive Gattoboxes. Source: link @tonlines

TONlines – News

@tonlines · Post #6875 · 21.04.2025 г., 11:30

Gatto | Official Channel: A New Chapter with Nessie #Nessie#GattoVerse The GattoVerse was once again visited by Nessie, revealed not to be a monster but a protective mother of her species. After hatching her offspring, Nessie passed the responsibility of their care to the event participants who achieved 1000 damage points, rewarding them through the league. Source: link @tonlines

TONlines – News

@tonlines · Post #6766 · 14.04.2025 г., 18:36

Gatto: Upcoming Mine Rescheduling Announcement #Aetherian#GattoVerse Gatto | Official Channel announces a rescheduling of the mine due to a portal opening in the Aetherian world. The next mine event, offering two opportunities with rewards, is scheduled for April 24th. Source: link @tonlines

TONlines – News

@tonlines · Post #6743 · 13.04.2025 г., 18:08

⚡️GattoVerse: A Star Marks a New Beginning #GattoVerse#Aetherian The GattoVerse is on the brink of transformation as a new star promises to illuminate the skies, potentially creating a portal to the ancient Aetherian world. This event could turn legendary tales into reality, and merchant Hat Mouse is poised to seize the moment. Source: link @tonlines