Установить свойства виджета в 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
🔥 Hey everyone, we've got some awesome news! Now you can switch the bot's AI model from gpt-4o-mini to gpt-4o, o1, or o3 using the command below:
/model
🚀 Yup, you heard that right! It’s like choosing from different ice cream flavors—each one has its own irresistible taste! 🍦
❓ Do you want fast and playful answers with gpt-4o-mini? Or are you after precise and calculated responses with gpt-4o? Maybe you're in the mood for a unique vibe with o1 or o3? The choice is all yours!
🙂 So, let's have some fun and see which model suits your style best. If you have any questions or even a cool joke, feel free to share it with us at:
🤩@OpenAI_helpdesk
GPT_o3_mini:
• Smarter than 90% of people
• Speed: 3/5
• Cost: about 90X
GPT_o1:
• Super smart but a bit slow (Speed: 1/5)
• Supports images
• Cost: about 300X
GPT_4o_mini:
• Our main ChatGPT engine
• Super fast (Speed: 5/5)
• Supports images and free tokens
• Only costs 150X!
GPT-4o:
• Speed: 4/5
• Intelligence: 3/5
• Supports images and free tokens
• Cost: about 36X per word + 900X per request
💱 You might end up with too few tokens, so it's better to buy tokens right away to fully enjoy all the bot's awesome features.
☺️ Stay happy and enjoy the bot!
➖➖➖➖🔻
💎@Chatgpt_OfficialNews – Stay Updated! ⚡️
🧠 BOT: @Chatgpt_OfficialBOT
#️⃣#ChatGPT#AI#OpenAI#TokenSystem#CryptoPayments#BotSupport#Update
➖➖➖➖🔺
🌟 Exciting News for Our Users! 🌟
We’ve upgraded our system with a token mechanism for seamless usage! 🎉 Here's how it works:
💡 Tokens are deducted based on the number of characters in your question and the bot’s response.
📥 Daily Bonus: Every day, you’ll receive a free token refill to keep chatting without interruptions!
💳 Recharge Options: You can now top up your balance using Telegram Stars and cryptocurrency payments (BTC, ETH, USDT, and more)! 🚀
Enjoy more flexibility and freedom with this new system. Thank you for being part of our community – stay tuned for more updates! 💬
➖➖➖➖🔻
💎@Chatgpt_OfficialNews – Join Us! ⚡️
🤖 BOT: @Chatgpt_OfficialBOT
📱#ChatGPT#AI#OpenAI#TokenSystem#CryptoPayments#BotSupport#CommunityDriven
➖➖➖➖🔺
#Advertisement
Secure Your Crypto with Paycio! 🔒
Paycio ensures you can send and receive digital assets quickly and securely using just your mobile number. Whether you're a beginner or an expert, Paycio makes it easy.
Join the crypto revolution with Paycio!
🌐 Website: https://www.paycio.com
🤖 Install the app from here: https://play.google.com/store/apps/details?id=com.paycio
#Paycio#CryptoSecurity#Trust#CryptoPayments#SecureTransactions
🚀 Exodus Launches Self-Custody Payments App for Bitcoin and Stablecoins
Exodus has introduced a new self-custody payments application, enabling users to spend Bitcoin and dollar stablecoins. According to NS3.AI, the app is compatible with merchants that accept Visa and Apple Pay, providing a seamless payment experience for cryptocurrency holders.
#Exodus#Bitcoin#Stablecoins#SelfCustody#CryptoPayments#Visa#ApplePay#Cryptocurrency#BTC
Thailand Considers Bitcoin Tourism Pilot
Thailand eyes Bitcoin pilot in Phuket, focusing on tourism, despite the Bank of Thailand's ban on crypto payments. Supported by Binance Thailand CEO. Read more here.
#Thailand#Bitcoin#Thaksin#Phuket#Binance#CryptoPayments#Tourism BankOfThailand #PilotProject
🚀 Welcome to the Future of Communication & Payments with Liberdus
🔐 A decentralized messaging + payment platform built for privacy, speed, and freedom.
✨ Features: • End-to-end encrypted messaging
• Instant crypto payments
• Decentralized network
• Ultra low transaction fees
• Built on powerful Shardus technology
• Community-driven ecosystem
➡️ No central control. No censorship. Just secure communication and financial freedom.
⚡️ Liberdus is combining blockchain technology with real-world messaging utility to create the next generation of Web3 communication.
🔵Telegram: https://t.me/liberdusofficial
🔴 Website: http://liberdus.com
🐦 X: https://x.com/liberdus
#Liberdus#Web3#Crypto#Blockchain#DeFi#Messaging#Decentralized#Shardus#Privacy#CryptoPayments
Mining Project Linked to Notcoin?
Emerging mining project possibly linked to The Open Builders, but not confirmed. Design resembles their work. Early supporters encouraged to invest, but caution advised due to potential volatility. Bitcoin has hit a new all-time hashrate of 1000 EH/s, with 40% concentrated in the US led by Foundry USA at 36.5% share. China still holds a significant portion of Bitcoin mining. In other news, Coinbase is considering tokenized stocks for its Base blockchain, while Ethena announces new products including an institutional synthetic stablecoin and a Telegram-based app. Phantom wallet team denies rumors of an upcoming airdrop or token launch.
#Mining#Bitcoin#Cryptocurrency#Notcoin#TheOpenBuilders#Ethena#Stablecoins#PhantomWallet#COIN#Base#Funding#CryptoPayments#Investing#Hashrate#Blockchain#DeFi#CryptoNews#Tech#US#China#Foundry