Установить свойства виджета в 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
🔰 AccuWeather MOD APK v8.12.3-3 🔰
MOD - (Premium / Pro)
ℹ️ Description:
AccuWeather MOD APK v8.12.3-3 (Premium / Pro) Mod APK Your local weather forecast, storm tracker, radar maps & live weather news Download AccuWeather Pro APK Premium
🆕 WHAT’S NEW:
In our effort to become your ideal weather app, we fixed a few bugs and optimized performance to give you an even more seamless experience.
➕ MOD:
Pro features unlocked;
Optimized graphics and cleaned resources for fast load;
Safe and Clean
No ADS
Category: #Weather🧩
Developer: AccuWeather 👨💻
App ID: com.accuweather.android🔐
Current Version: VARY ✅
Latest Update: 2023-08-28 09:23:51 ♻️
Content Rating: Everyone 👀
Requirements: 5.0 📲
Enjoy 😊😘😊😘😊😘😊😘😊
https://t.me/joinchat/KOQ8o_8ns24yZTE8
@EverythingMe
Clima ☁
Beautiful, minimal, and fast weather app.
Features:
• Beautiful, minimal UI
• 8-day forecast
• Imperial units support
• Dark and light themes
• No ads or trackers
Download: https://f-droid.org/packages/co.prestosole.clima
https://github.com/Lacerte/clima
#weather
@foss_Android
💧Rainy season 2024/25 in Indonesia
☔ The rainy season in central Bali has already begun, however, the region is currently experiencing the effects of a La Niña phenomenon with weak intensity.
📆 This phenomenon has the potential to increase rainfall compared to normal conditions, although the effect so far has been negligible. The Agency of Meteorology, Climatology and Geophysics estimates that the entire Bali region will enter the rainy season in December 2024, with the peak in late January-February 2025.
source: detik
@BaliNews
#weather
🌪️⚡DEADLY MIDWEST TORNADO OUTBREAK LEAVES 8 STATES DEVASTATED
🔹 At least 12 confirmed tornadoes touched down across Kansas, Iowa, Illinois and Nebraska destroying entire neighborhoods 🏠
🔹 Over 70,000 residents remain without power as utility crews work around the clock to restore electricity grid ⚡
🔹 FEMA estimates $25,000 average property damage per household with total losses exceeding $2 billion statewide 💰
🔹 Governor declares state of emergency as flash flooding traps dozens of motorists on Interstate highways 🚨
National Guard deployed to assist with search and rescue operations. Weather service warns more storms possible 🔥
#USNews#weather
@america
📰Weather Tag
In the Beta version of Telegram for Android, you can add a weather tag to your story. You can only add the weather for your current location. So your device's location access must be turned on to add the tag. It is also possible to change the colors of the tag.
#Weather | #Stories
👉The TG Times
🌋Levotobi Laki Laki eruption in Indonesia – current status and forecast
📰 The Levotobi eruption took on an explosive character. On November 18 2024, the volcano's vent fired a lava bomb that reached residential areas.
ℹ️ Local authorities have set up an information centre to support tourists affected by the eruptions. It provides various types of assistance, including evacuation to neighbouring provinces such as Bali. Also, the national tourism board Wonderful Indonesia has issued a travel guide for the East Nusa Tenggara area.
@BaliNews
#accidents#weather
Geometric Weather
A lightweight, powerful, open-source Material Design weather app.
Geometric Weather is a light and powerful weather app that provides you with real-time temperature, air quality, 15-days weather forecast, and accurate time-sharing trends.
Features:
• Beautiful Material Design Interface
• Global Weather Data
• Automatic Dark Mode
• 15 Days And 24 Hours Overview data
• Severe weather and precipitation alerts
• Large selection of home screen widgets for at-a-glance information
• Weather Notification And Forecast
• Alert Information
• Supported weather providers:AccuWeather,OpenWeather,Météo France
• Multiple UI Styles
• Live Weather Wallpaper
Download - https://f-droid.org/packages/wangdaye.com.geometricweather/
https://github.com/WangDaYeeeeee/GeometricWeather
#new#weather
@foss_Android
🌦ПРОГНОЗ ПОГОДЫ
📅 24 АПРЕЛЯ
🌤 Переменная облачность, без осадков.
🌬Ветер восточный 7-12 м/с.
🌡Температура ночью 11-16°, днем 24-29°.
📅 25 - 28 АПРЕЛЯ
🌤 Переменная облачность, без осадков.
🌬Ветер восточный 7-12 м/с, 26-27 апреля местами возможно усиление до 13-18 м/с, в отдельных районах с пыльным поземком.
🌡Температура 25-26 апреля ночью 13-18°, днем 26-31°, 27-28 апреля ночью 15-20°, днем 28-33°.
Источник:https://hydromet.uz
#погода#weather
@Samarkand100 - Подпишитесь
🌦ПРОГНОЗ ПОГОДЫ
📅 23 АПРЕЛЯ
🌤 Переменная облачность, дождь, возможна гроза.
🌬Ветер западный 7-12 м/с.
🌡Температура ночью 13-18°, днем 18-23°.
📅 24 - 27 АПРЕЛЯ
🌤 Переменная облачность, без осадков.
🌬Ветер восточный 7-12 м/с, 26-27 апреля местами возможно усиление до 13-18 м/с, в отдельных районах с пыльным поземком.
🌡Температура 24 апреля ночью 11-16°, днем 24-29°, 25-27 апреля ночью 13-18°, днем 26-31°.
Источник:https://hydromet.uz
#погода#weather
@Samarkand100 - Подпишитесь
🌦ПРОГНОЗ ПОГОДЫ
📅 22 АПРЕЛЯ
🌤 Переменная облачность, местами дождь, возможна гроза.
🌬Ветер восточный с переходом на западный 7-12 м/с, местами возможно усиление до 13-18 м/с, в отдельных районах с пыльным поземком.
🌡Температура ночью 15-20°, днем 22-27°.
📅 23 - 26 АПРЕЛЯ
🌤 Переменная облачность, 23 апреля местами дождь, возможна гроза. 24-26 апреля без осадков.
🌬Ветер западный с переходом на восточный 7-12 м/с.
🌡Температура ночью 13-18°, лишь 24 апреля 11-16°, днем 23 апреля 18-23°, 24-26 апреля повышение до 28-33°.
Источник:https://hydromet.uz
#погода#weather
@Samarkand100 - Подпишитесь
🌦ПРОГНОЗ ПОГОДЫ
📅 21 АПРЕЛЯ
🌤 Переменная облачность, местами возможен дождь, гроза
🌬Ветер восточный 7-12 м/с, местами усиление до 15-20 м/с, с пыльным поземком.
🌡Температура ночью 13-18°, днем 24-29°.
📅 22 - 25 АПРЕЛЯ
🌤 Переменная облачность, 22-23 апреля местами возможен дождь, гроза. 24-25 апреля без осадков.
🌬Ветер западный с переходом на восточный 7-12 м/с, 22 апреля местами возможно усиление до 13-18 м/с.
🌡Температура ночью 22-23 апреля 13-18°, 24-25 апреля 11-16°, днем 22 апреля 22-27°, 23 апреля 18-23°, 24-25 апреля 24-29°.
Источник:https://hydromet.uz
#погода#weather
@Samarkand100 - Подпишитесь