Установить свойства виджета в 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
Binance, the world's largest cryptocurrency exchange, has achieved a major milestone in Indonesia. The company's subsidiary has successfully obtained a regulatory license from the Indonesian authorities, paving the way for expanded operations and increased legitimacy in the country.
#Bullish🔥
#BTC, did multiple retest back to the zone and kinda have it break and retest. Price already rejecting the zone multiple times, which is sort of #bullish as of now. #ETFs also get approvals, good to see price sustaining over the zone. Well, if #Bitcoin remains silent over this, then we can see a good rally in alts soon.
By Crypto Australia
⚡️ Sentiment notes a decrease in the number of wallets with a non-zero balance 🪙#BTC, which may mean that some participants will enter the cache before the US elections. The experts of #Sentiment consider this development of the situation to be #bullish for #BTC after the elections are held...
📈Bullish Pattern - Three White Soldiers.
A. How to recognise it?
• There must be a preceding downtrend.
• Three consecutive long green candles observed.
• The second and third candle opens within the body of the preceding one but closes higher than the preceding one.
B. What is the psychology behind?
•The first long green candle signals that the bears are exhausted after the prolonged downtrend and the bulls start to take over. The bulls continue the rally with the subsequent two candles closing higher.
C. How do we trade it?
• Look for the Three White Soldiers at the bottom of a downtrend.
•Wait for the fourth candle to close above the high of the third candle to confirm the reversal.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the first green candle.
#patterns
#fibonacciacademy
#bullish
@fibonaccisyndicate.
Channel: BULLISH CRYPTO ( VIP OFFICIAL )
Members: ~2.69K
💢 Username: @officialbullishcrypto
Description:
At Bullish Crypto Comumnity! You can find tested strategies, powerful tools, and experienced traders to arm you with knowledge.
🏷 Tags: #crypto_fx_trading
#crypto#bullish#signals#investment#money
https://telegramchannels.me/channels/officialbullishcrypto
Despite the bear market, DWF Labs is choosing to double down on crypto innovations.
"I think the key to #innovation in #Web3 is decentralization. Many projects that we are seeing and decided to invest into, are bringing to the table real decentralization value.
We have experienced massive #tech acceleration especially during crypto winter or previous bear cycles.
That is why we are so #bullish about funding the next wave of #crypto innovation. This year alone, we funded more than 50 projects."
- Andrei Grachev (Managing Partner, DWF Labs)
Read full interview here.
📈Bullish Pattern - PIERCING
A. How to recognise it?
• There must be a preceding downtrend.
• A red candle followed by a green candle.
• The green candle opens with a gap-down and closes at 50% or above of the real body of red candle.
B. What is the psychology behind?
• The red candle implies the control of the bears following a prolonged downtrend.
• In next session, the market opens below the low of the red candle, suggesting continuation of the bearish forces.
• The bears then lose momentum, the bulls conquer and lead the price up during the session, and eventually manage to cover 50% losses or more from the previous session.
C. How do we trade it?
• Look for the Piercing at the bottom of a downtrend.
• Wait for the next candle to close above the high of the green candle to confirm the existence of bullish force.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the green candle.
#patterns#bullish#trading#fibonacciacademy
@fibonaccisyndicate
📈Bullish Pattern - HAMMER🔨
A. How to recognise it?
• There must be a preceding downtrend
• It looks like a square lollipop with a long stick.
• The closing price is above or near the opening price, forming a tiny body.
• The real body could be green or red. It has no or little upper shadow.
• The lower shadow is at least twice of the length of the real body.
B. What is the psychology behind?
• Similarly to Dragonfly Doji, when the market opens, the bears continuously drag the price down during the session, resulting in a long lower shadow.
• The bulls fight strongly and conquer the bears by pushing the price above or near the opening level, forming a little square body.
• The longer the lower shadow, the more effective the bullish signal. It tells us that the bulls are strong enough to conquer the bears who once dragged the price so low.
C. How do we trade it?
• Look for the Hammer at the bottom of a downtrend.
• Wait for the next candle to close above the high of the Hammer to confirm the existence of bullish force.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the Hammer.
#patterns#bullish#trading#fibonacciacademy
@fibonaccisyndicate
📈Bullish Pattern - Dragonfly Doji
A. How to recognise it?
•There must be a preceding downtrend.
• It looks like a T letter.
• The opening, highest and closing price are same.
• It has no real body but a long lower shadow.
B. What is the psychology behind?
• When the market opens, the bears drag the price all the way down, resulting in a long lower shadow. • The bulls fight strongly and eventually manage to push the price back up to the opening level. • The longer the lower shadow, the more effective the bullish signal. It tells us that the bulls are strong enough to conquer the bears who once dragged the price so low.
C. How do we trade it?
• Look for the Dragonfly Doji at the bottom of a downtrend. • Wait for the next candle to close above the high of the Dragonfly Doji to confirm the existence of bullish force. • Open a long position upon confirmation. • Place a stop-loss below the low of the Dragonfly Doji.
#patterns
#fibonacciacademy
#bullish
#trading
@fibonaccisyndicate