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

Резултати

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

Пребарај: #shooter

当前筛选 #shooter清除筛选
APKPure_Official

@apkpurechannel · Post #2260 · 23.02.2025 г., 15:00

🔁[MOD UPDATE]🔁 FRAG Pro Shooter MOD APK 4.5.2 UPDATE Experience thrilling FPS gameplay with unique characters, vibrant maps, and exciting modes. 🎮💥 Team up and show your skills today! 🕹Download Now🕹 Game Features: - Publisher: Oh BiBi - Version: 4.5.2 - Size: 207.4 MB - Category: #Action, #Shooter - MOD Info: Unlimited Resources Add @APKFreeDownloader_Bot to get any apk you want.

MoonPlay

@moonplay_official · Post #39 · 23.06.2024 г., 16:13

SHOOT ‘EM UP 💫 Hey Space Cadets! This Friday brought you one more way to earn 💸. We’re over the moon to announce the launch of a fascinating mini-game, Star Dust💫, on To The Moon! Get ready to navigate your ship through an asteroid belt and blast your way to cosmic riches. ✅Asteroid Blasting Action: Use your ship's blaster to shoot and destroy falling asteroids. Different types of asteroids offer different amounts of Space Bucks, so aim and fire! ✅Finger Press Control: Keep your finger pressed on the screen to fire. ✅Level-Based Rewards: The amount of Space Bucks you collect for shooting asteroids is based on your player level. The higher your level, the bigger your rewards! ✅Durable Ship: Don’t worry if you miss a few asteroids—your ship is built to withstand the hits. Play to your heart’s content, once you’ve had enough, just press the cross at the upper right corner to exit and collect space bucks. Ready to dive into the asteroid belt and rack up those Space Bucks? Head to the Play tab andget started🚀. May your blasters be swift and your aim true! Stellar adventures start here:@moon_land_bot🚀 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#ecosystem#blockchain#gamefi#web3#wenlisting#airdropsoon#communityfirst#taptap#clicker#game#invitefriends#shooter

Видеотека 📼

@videotekashow · Post #13599 · 05.06.2025 г., 03:45

«Я готов хоть траншеи копать, и актерство — не главное в моей жизни». Сегодня Марку Уолбергу исполнилось 54 года. #ВИДЕОТЕКА #MarkWahlberg #BoogieNights #TheCorruptor #TheItalianJob #TheDeparted #Shooter #WeOwnTheNight #TheFighter #PainAndGain #PatriotsDay #ArthurTheKing