Установить свойства виджета в 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
Обонятельные луковицы мыши в наноскопическом разрешении. За этой видяшкой примерно петабайт (><) данных.
#expansion#microscopy
Экспансионная микроскопия позволяет добиться фантастического разрешения, но у неё есть, конечно проблемы. Одна из них неочевидная, пока об этом не задумываешься. Но логичная.
Образец становится большим. Иногда большим чем рабочая дистанция объективов, соответственно заметная часть нашего великолепного образца с нанотдетализацией остаётся за кадром.
Что делать если все таки хочется рассмотреть объект целиком?
Авторы статьи Mesoscale volumetric fluorescence imaging at nanoscale resolution by photochemical sectioning предложили интересное решение. Они сделали гель для экспансии такого состава, который разрушается под действием УФ, что позволило им нарезать (лазером) гель в процессе сьемки. Фактически они сделали оптический FIB (метод из электронной микроскопии, где образец нарезают пучком ионов).
В комментах видео с подробностями из твиттера автора статьи Ruixuan Gao
In the latest episode of DWF Chats, we hosted:
🔹Micky Watkins (Founder and CEO, World Mobile Group)
🔹Zachary Vann (Head of Token, World Mobile Token)
Hear more about WMT's scalability and their #expansion roadmap, the utility of WMT token and how you can get involved in WMT #community✨
Full interview here.
//
About:
▫World Mobile Token aims to build a #decentralised telecommunication network to deliver affordable, quality Internet access to the unconnected.
Visit http://worldmobiletoken.com to find out more.
🪐 The end of the universe is a cosmic puzzle with several real scenarios proposed by scientists, each based on clues from galaxies like Messier 87 and ancient light observed by telescopes. One idea is the "Big Bounce," where the universe’s expansion might someday reverse due to gravity, causing everything—including stars such as Betelgeuse and black holes like Sagittarius A*—to collapse back into an ultra-dense state, possibly leading to another cosmic cycle. Unlike the "Big Freeze" or "Big Rip," the "Big Bounce" is still debated, but it shows how the fate of the universe could depend on the balance between gravity and mysterious forces such as dark energy. ✨
#universe⚡#cosmology⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Over billions of years, the expansion of the universe—measured by observing distant galaxies like Messier 87—will stretch space so much that the light from other galaxies will eventually fade from view. Long after stars like our Sun burn out, only the dead remnants of stars and black holes will remain, and as cosmic expansion continues, even these may become isolated in a cold, dark universe, ending with silent emptiness. ✨
#universe⚡#fate⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Sun, along with all stars in the Milky Way, will eventually run out of fuel and end as a white dwarf—a small, cool stellar remnant. Over trillions of years, even white dwarfs like the one in Messier 4 will cool and fade to black, leaving the universe filled with cold, dark remnants, while galaxies such as Andromeda drift farther apart as cosmic expansion continues. ✨
#universe⚡#fate⚡#expansion⚡#stars⚡#nasa⚡#galaxy⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 One of the great cosmic mysteries is how the universe will end, and scientists look to real clues from galaxies like Andromeda and stars such as the Sun to guide their ideas. Some theories suggest the universe might continue expanding forever, causing galaxies to drift so far apart that even light from Andromeda will never reach us again, while others consider whether the universe’s own gravity could eventually pull everything—stars, planets, and even black holes—back together in a colossal collapse, erasing all known cosmic structures. ✨
#universe⚡#fate⚡#expansion⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
寒蝉鸣泣之时 虚崩篇
▎介绍
■■ <注意>.
不提供任何担保。 请自行承担使用风险。
日暮之夜 "的版权归 Circle 07th_Expansion 所有。
日暮之夜 "的版权归 Circle 07th_Expansion 所有。
Mui Mui Mui 制作的文库。 使用 Mui Mui 制作的文库 (
http://d.hatena.ne.jp/eiji8pou/20050914/1126709682)。
该库的版权归 Mui Mui 所有。 资料库版权归 Mui Mui 所有。
世界设定。
节日音乐版和碎片旋转后的世界。
如果没有玩过林松里版,故事可能会显得跳跃。
古特家族的设定与主家族有明显不同。
故事的主角是敬岚和敬石。 (故事是关于敬岚和敬志的)。
有仇恨! 注意事项
▎获取
PC仓库
▎标签
系统:#PC
类型:#galgame#NSWF#汉化
系列:#寒蝉鸣泣之时
出版:#Expansion