Установить свойства виджета в 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
💡 OpenAI Valuation Soars Above $100 Billion
OpenAI is reportedly in talks to raise new investments, pushing its valuation to over $100 billion. Thrive Capital is set to contribute $1 billion to this funding round, aimed at enhancing computing power and covering operational costs. OpenAI staff may get the chance to sell shares later this year. Despite the impressive valuation, the company faces potential losses of $5 billion in 2024, emphasizing the need for this capital infusion.
#AIInvestment#OpenAI#TechFunding
Ryvn Secures $500K Funding
Ryvn raises $500K to empower startups with on-prem SaaS deployment and management, streamlining operations from a single app.
#Funding#SaaS#Startups#OperationalManagement#TechFunding
Bureau Secures $30M Funding
Bureau, a trust network focused on identity verification, compliance, and fraud prevention for modern businesses, has raised $30 million. The funding round closed on December 18, 2024. 🏦
#Funding#IdentityVerification#Compliance#FraudPrevention#TechFunding#BusinessSolutions#Investment#Startups
Motion.io Secures $3.17M Funding
Motion.io raises $3.17M on December 18, 2024, to enhance their white-label client portals. The funding will support automating client onboarding and improving file, signature, and feedback collection processes.
#MotionIo#Funding#ClientPortals#Automation#Onboarding#TechFunding#Feedback#Signatures#WhiteLabel#Startup#Investment
Alvie Raises $2.19M for HUGO
Alvie has secured $2.19 million to advance HUGO, the first digital assistant aimed at optimizing the spraying of phytosanitary products and bio-controls, as announced on December 19, 2024.
#Alvie#HUGO#Funding#AgTech#DigitalAssistant#Phytosanitary#BioControls#Innovation#TechFunding#SustainableAgriculture
CreatorBid Raises $2.5M; Google Invests in AI
AI-driven platform CreatorBid raised $2.50M in a public sale, achieving a $25M FDV via Binance Wallet. Meanwhile, Google invests $1B in AI startup Anthropic as the company targets a $2B funding round. Notably, Nebius closely trails Yandex in market cap with worth of $9.3B. Significant movements highlight ongoing innovation in the AI and crypto sectors.
Full news: CreatorBid | Google Invest | Divvy Homes Sale | Nebius Market Cap
#AI#Crypto#VC#Fundraising#Google#Anthropic#CreatorBid#Investment#TechNews#Startups#MarketCap#DivvyHomes#Innovations#Binance#Stablecoins#TechFunding#Nebius
Mantis Robotics Secures $5M Funding
Mantis Robotics has raised $5M on December 16, 2024, to develop the Mantis Robot, touted as the fastest and safest industrial robot with physical intelligence.
#MantisRobotics#Funding#Industrialrobot#Investment#Technology#Innovation#Manufacturing#Robotics#Automation#AI#Safety#Fastest#PhysicalIntelligence#Engineering#RoboticSystems#TechFunding#Startup#RoboTech
CLO Virtual Fashion Raises $34.81M
CLO Virtual Fashion successfully raised $34.81 million in funding, with a funding round occurring on December 16, 2024. For more information, visit their website: CLO Virtual Fashion.
#Funding#CLOVirtualFashion#Investment#Fashion#Tech#3DModeling#VirtualReality#FashionTech#Innovation#Startup#TechFunding#Capital#December2024#Growth#Industry#Development#Design#FashionIndustry#DigitalFashion
Zhipu AI Raises $411.82M
Zhipu AI has raised $411.82 million as of December 17, 2024. The company co-developed the GLM-130B model, resulting in a dynamic knowledge engine termed the 'knowledge double wheel'. They also launched the cognitive model platform Bigmodel.ai, featuring products like CodeGeeX and CogView, which provide intelligent API services connecting users across various sectors.
#ZhipuAI#Funding#AI#Bigmodel#GLM130B#CodeGeeX#CogView#API#Tech#KnowledgeMap#CognitiveModels#Intelligence#DigitalHumans#MachineLearning#DataScience#Innovation#Research#TechFunding#Startups#Development
PulseAd Raises $2M Funding
PulseAd, an AI-powered global retail media platform, has secured $2 million in funding as of December 19, 2024. The platform is designed to enhance Amazon seller success.
#PulseAd#Funding#AI#RetailMedia#Amazon#GlobalMarket#ECommerce#TechStartup#MediaPlatform#SellerSuccess#Investment#DigitalMarketing#TechFunding#SaaS#OnlineRetail#Advertising#InnovativeTech#GrowthFunding#BusinessExpansion
MRI Simulator Secures $3.5M
Corsmed has successfully raised $3.50M to enhance its MRI simulator, which provides an affordable, realistic training solution for students and technicians. This technology allows hands-on experience for just 1% of the cost of traditional MRI scanners, expanding training opportunities significantly.
#Corsmed#MRI#Simulator#Healthcare#Training#EdTech#Innovation#Financing#MedicalTraining#TechFunding#Startup#Students#Technicians#AffordableHealthcare#HandsOnTraining#SkillsDevelopment#Technology#Upskilling#AffordableTech#MedicalEducation