Установить свойства виджета в 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
Coronado Island 🎏
Рядом с Сан Диего расположился Coronado Island. Небольшой островок, известен дорогими отелями и пляжами
На этом пока материал с Калифорнией закончился, вернулся в родную гавань
#CA
Коллеги делятся фотографиями с Калифорнийского парка Chino Hills State Park, красота нереальная.
В этом году зимой были проливные дожди, из-за этого бум маков.
#CA
#review
#shortStory#beginning
#CA
Grabbing her wrist. Rubbing the small space between her palm and the soft skin covering her veins. Traveling to the crease of her arm. She had worked hard today. Her clients were pleased with the outcome. Each one feeling a sense of ease and comfort from the constant energy surrounding them. Some came because pain in the physical sense. Others because something deeper. More hidden and yet still calling out. It wasn’t something she had learned in text or class. It was a part of her. This unending need to draw their pain, their confusion into her core. Transform it back into something able to give them rest. Her hands were something more than flesh and her heart was more than beat. She was filled with something that could not be described, only felt. A smile crossed her lips as the gratitude filled her soul. In a world where so many were without purpose. She had found hers.
#review#CA#poetry
Love isn’t the glance of eyes that lock in time. The words spoken of passion. A need or want for embrace. Love isn’t the nostalgia one feels with reminiscing. Love isn’t the sacrifice or the control of one’s fate. It isn’t the constant knowing of place or time. The inside workings of the mind. It’s the acceptance of separation. Of knowing this path is neither yours nor mine. It’s the walking of foot steps side by side allowing the division that plays in time.
#CA#review#shortStory
Listening to the rustling of the trees. Feeling the warmth of the sun. A moment a thousand words couldn’t describe. A stillness so profound she could feel the energy beneath the ground. Stirring below her feet. A vibration that traveled through her limbs and into her soul. She sighed with relief. A smile appearing at the corners of her mouth. A light within her eyes. This was perfect. She thought of how many moments wasted. Always staying busy. Having a mindset of lack. A constant want for more. How disturbing to be in that whirlwind. Never alone yet always cut away. She wondered how many others were in this realization. This dawning of a wisdom beyond age and time. She glanced at her palms as she turned them to the sky. Feeling the wind but never seeing it, all it’s wonder and beauty. A contentment filled her as she closed her mouth only letting her thoughts become her sound speaking to the energy all around and patiently waiting for its echo from the ground.
#review#shortStory#CA
What was it that transformed her? Were people just born like this? No it was like a path that swirled within her journey. An awakening. Suffering had been her constant and chaos her normal. Her escape was her imagination, her song, her dance. The way she saw such light touch everything. Knowing she was protected even though her physical world would prove otherwise. She had a blood line but not a family. She spoke with nature. Saw herself in creatures. Believed in the impossible. It wasn’t something she did that made the difference. When trying things it always seemed like an uphill battle. When allowing things. Her life shifted. She had a realization that everything in life had its place.
Остатки рандома из Сан Диего
В прибрежной зоне часто приливы/отливы. Можно увидеть прикольную живность, которая запряталась в камнях, но должно повезти. Нам не повезло
Зато повезло почти заехать на военную базу. Если выставить в картах BMW Cabrillo National Monument, то есть шанс, что он повезёт вас не туда, хотя въезд будет очень похож. С единственным отличием - на въезде будут военные, которые вас остановят и заберут ID на проверку
Ещё оказывается в серии Книг волшебника страны Оз больше книг чем я себе представлял, а писатель Фрэнк Баум жил в Калифорнии в своём доме "Ozcot" (от "Oz" и "cottage"), где и написал большую часть серии. Первую книгу он написал живя в Чикаго
#SanDiego#CA