Установить свойства виджета в 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
http://stackoverflow.com/questions/7110604/standard-way-to-create-debian-packages-for-distributing-python-programs
My final goal should be that of creating a "binary" .deb package. Such package will be platform independend (32/64 bit) as all python programs are such.
To create a "binary" #package I need first to create a source package.
To create the source package I can use either CDBS or debhelper. Debhelper is the recommended way for beginners.
The core of creating a source package is populating the DEBIAN directory in the source directory with a number of files clarifying where files need to be copied, what copyright and licensing scheme they are subject to, what dependencies they have, etc...
Step #4 can be largely automated the dh_makecommand if the python source also comes with a distutils' setup.py script.
@HTMLWebShotBot
#repo - GitHub
#package - PyPI
- Send a URL to get the screenshot of that webpage.
- Send a .html file to get a screenshot of how it would appear on the web.
Do follow me onGitHub, 200 soon🎉
~ @BotzHub
@DetectProfanityBot
#repo - GitHub
#package - PyPI
- This bot can delete messages containing abuses from your group.
- Add the bot to your group and make it admin, and it'll keep your group clean from abuses.
- Group privacy is enabled. The bot has to be made admin in the group, for it to filter abuses.
- False positives can be removed, if reported in the chat.
~ @BotzHub
Kerakli package va kutubxonalarni ulashib borishda davom etamiz!
Vue js yordamida slider qilmoqchi bo'lganlar uchun sodda package. Swiper js kabi murakkab fungiyalarga ega emas. Lekin kichikroq proyektlarda bemalol ishlatsa bo'ladi. Install qilish va ishlatish juda sodda tarzda berilgan.
📔 Ishlatib ko'rish uchun
#vue#package
☑️@valisherbotirov
#套餐结构调整通知
由于当前所有线路升级为:内网中转,成本大幅上涨
我们将最迟在10月上旬完成对套餐结构调整(主要针对流量和价格的中幅度调整)
AyuCLouD-Services 运营团队 敬上!
#Package structure adjustment notice
As all current lines are upgraded to: intranet transfer, the cost has risen sharply
We will complete the adjustment of the package structure by early October at the latest (mainly for medium-range adjustments in traffic and prices)
Sincerely, AyuCLouD-Services Operation Team!
http://www.debian.org/doc/packaging-manuals/python-policy/ch-python.html
At any given time, the binary #package python3 will represent the current default #Debian Python 3 version; the binary package python will represent the current default Debian Python 2 version. As far as is reasonable, Python 3 and Python 2 should be treated as separate runtime systems with minimal interdependencies.