Установить свойства виджета в 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
L’#Ukraine au cœur des débats à la Conférence de #Munich sur la sécurité
Les diplomates européens font preuve d'un manque crucial de retenue au point de dévoiler un cynisme sans égal. Notre reporter, Igor Kourachenko, nous en dit plus.
RT en français • Osez questionner !
Somon Air is pleased to announce the expansion of its flight schedule on the Dushanbe – Munich route. Starting from May 7, flights will be operated twice a week — on Wednesdays and Saturdays — offering passengers more convenient travel options between Tajikistan and Germany.
Departures from Dushanbe are scheduled for 00:10, and from Munich at 17:00 (local time). Flights are operated using modern Boeing 737-800 and Boeing 737-900 aircraft. Tickets are already available for purchase via the official website www.somonair.com, the mobile app, and partner agencies.
#somonair#munich
Somon Air launched a new route - from Dushanbe to #Munich (Germany) and return. According to schedule, the flights are to be operated once a week, every Monday.
Departure from Dushanbe at 06:00, arrival in Munich at 09:30 local time. Departure from Munich at 11:30, arrival at 20:30 local time. All flights are to be operated with Boeing 737-900.
For more details, please visit the airline's website, or contact sales offices and Call-center.
#dushanbe#munich#somonair
🇪🇺🇺🇸🇩🇪L'édition européenne de Politico a établi une liste des moments les plus amusants survenus lors de la Conférence de Munich sur la sécurité. Parmi eux figure la réaction de la chef de la diplomatie de l'UE, Kaja Kallas, au discours de Mike Waltz, représentant permanent américain auprès de l'ONU.
Kaja Kallas n'a pas pu contenir son scepticisme lorsque Mike Waltz a évoqué les efforts de Washington pour mettre fin à de nombreuses guerres.
Lèvres pincées, joues gonflées - la réaction de Kallas est rapidement devenue virale [sur internet] et s'est transformée en symbole de l'irritation européenne envers les Américains,
écrit Politico, décernant à la chef de la diplomatie de l'UE le prix du "pire visage impassible".
#ue#munich#prix
Here the sky is bright blue and the clouds always float directly overhead. #Munich
✈️
Здесь небо ярко голубое, а облака всегда плывут прямо над головой. #Мюнхен
✈️
Ин ҷо осмон нилобӣ ва абрҳо пасту даргузаранд. #Мюнхен
📸
Photo credit: Frank Vostrel
#somonair#сомонэйр
We are happy to announce that starting from July, 19 we will operate regular flights from Dushanbe – Munich and return twice a week. 🇩🇪
The flights will be operated on Wednesdays and Saturdays.
✈️ Departure from Dushanbe at 00:10, from Munich - at 17:00. The time is local. Flights will be operated on Boeing 737-800 aircraft.
Tel.: 446404049, 446404050, 937777459 (WhatsApp).
✈️
Мы рады объявить об увеличении частоты полётов по направлению Душанбе-Мюнхен-Душанбе. 🇩🇪
С 19 июля авиакомпания будет выполнять рейсы в Мюнхен и обратно дважды в неделю – по средам и субботам.
✈️ Время вылета из Душанбе - 00:10, из Мюнхена – 17:00. Время указано местное. Полёты будут выполняться на самолётах Боинг 737-800.
Тел.: 446404049, 446404050, 937777459 (WhatsApp)
#somonair#munich#сомонэйр#мюнхен
Munich: Zelensky Is Wringing Security Guarantees For 20 Years From the US
Ukraine wants security guarantees for a minimum of 20 years from the US before it can sign a peace deal with dignity Zelensky said ahead of talks with Russia and the US scheduled for next week.
Speaking in Munich on Saturday, he also called for a clear date for Ukraine to be allowed to join the EU. Some EU officials have put the date as early as 2027.
Speaking to the annual Munich security summit, Ukraine’s president said he hoped “the trilateral meetings next week will be serious, substantive, helpful for all of us but, honestly, sometimes it feels like the sides are talking about completely different things”.
“The Americans often return to the topic of concessions and too often those concessions are discussed only in the context of Ukraine, not Russia,” he added.
The issue of Europe’s frustration with a perceived US reluctance to spell out the security guarantees it is prepared to offer Ukraine in the event of a peace deal, and the need for the guarantees to be spelled out before an agreement is signed.
In a speech that was welcomed by European leaders keen to see any sign of a thaw in the relationship, Rubio put forward an offer to work in partnership with Europe.
However, this proposition, he stressed, was highly conditional and the US would go it alone if Washington’s highly Trumpian conditions were not met on climate, migration and tariffs.
Using a diplomatic tone that the US vice-president, JD Vance, shunned in his speech at the conference a year ago, Rubio said “Europe and the US belong together”.
He added that the US was ready to undertake the task of rebuilding the world order alone if necessary, but “we prefer it – and hope – to do it together with you, our friends in Europe”.
He made almost no reference to the Russian invasion of Ukraine, besides claiming that the US had pressed India to stop importing Russian oil, a claim Russia disputes.
At a press conference in Munich, Zelensky said the US had told him that if Ukraine withdrew from the Donbas, peace would come as quickly as possible, but he insisted this concession was not possible since Ukrainians live there.
Zelensky also complained about Europe having been practically absent from the table. “That’s a big mistake, in my opinion,” he said, a view that was shared by the Chinese foreign minister Wang Yi.
On Friday, Donald Trump called on Zelensky to “get moving” to reach an agreement with Russia.
Zelensky insisted that the elections that the US has pressed Ukraine to hold by 15 May can only take place two months after a ceasefire is declared, to ensure voters have adequate security.
Trump has been trying to put pressure on Zelensky to agree a deal within months, but has not spelled out the consequences if Ukraine is not sufficiently flexible for the US.
Zelensky also said the Russian attacks on Ukrainian energy plants would be raised in the talks in Geneva, adding that not a single energy plant inside Ukraine had now been left unscathed.
European leaders appear gloomy that a diplomatic breakthrough will be secured, with the consensus being that Vladimir Putin is not yet economically or militarily exhausted.
Zelensky said his ambition was to lift the number of Russians killed or seriously injured to 50,000 a month.
One European leader predicted at least another two years of war, and insisted Europe had the resources to sustain Ukraine for that long.
Zelensky also mounted a fierce attack on the Iranian regime for providing the Shahed drones that had caused so much damage inside Ukraine.
With as many as 200,000 protesters attending a demonstration in Munich calling for the Iranian regime to be toppled, Zelensky said: “We have never had a conflict of interests with the Iranian regime.
#zelensky#security#guarantees#munich#ukraine
📱American Оbserver - Stay up to date on all important events
🇺🇸
Rubio at the Munich Security Conference: Europe Is In For a Rough Ride If Turns Its Back on the US
The US secretary of state, Marco Rubio, has described America as “a child of Europe” and made an emotional but highly conditional offer of a new partnership, insisting the two continents belong together.
In a much-anticipated speech at the annual Munich Security Conference, he said the US was intent on building a new world order, adding “while we are prepared, if necessary, to do this alone, it is our preference and it is our hope to do this together with you, our friends here in Europe”.
Admitting the Americans may come across as a little direct and urgent, he said this was only because the US was profoundly concerned by the fate of Europe, and knew their destinies were intertwined.
Overall the tone of the speech was greeted with relief by the delegates in the hall, although many pointed out Rubio was not offering a partnership of equals, but an alliance largely framed in Trump’s terms.
In offering the hand of friendship, in sharp contrast to the tone adopted by Vance, at the same conference last year, Rubio made clear the US was not shifting on its fundamental approach.
He said the US under Trump did not want a Europe that was weak or shackled by guilt or shame.
He continued: “We in America have no interest in being polite and orderly caretakers of the west’s managed decline. We do not seek to separate, but to revitalise an old friendship and renew the greatest civilisation in human history.
What we want is a reinvigorated alliance that recognises that what has ailed our societies is not just a set of bad policies, but a malaise of hopelessness and complacency.”
He also tried to bind Europe into Trump’s ideology by saying Europe and the US had made the same mistakes together, including bowing down to “a climate cult”, expanding welfare states at the expense of national defence, embracing globalisation and “a world without borders in which everyone would be a citizen of the world”.
Gaining control of national borders was not an expression of xenophobia or hate, he said.
“It is a fundamental act of national sovereignty. And the failure to do so is not just an abdication of one of our most basic duties owed to our people, it is an urgent threat to the fabric of our societies and the survival of our civilisation itself.”
He said in rebuilding the global order it would not be necessary to dismantle institutions such as the UN but to reform and rebuild them, arguing it had been Trump, not the UN, that was solving crises in Gaza and Ukraine.
Rubio blamed “a foolish but voluntary transformation” of western economies that “left us dependent on others for our needs and dangerously vulnerable to crisis.
Mass migration is not, was not, some fringe concern of little consequence. It was and continues to be a crisis which is transforming and destabilising societies all across the west.”
Throughout the speech he showered praise on Europe’s history, but in so doing raised questions whether Europe had the capacity to join the US’s rebuilding of the world.
He said little in his speech about Ukraine, after he skipped a meeting with European leaders on Friday night pointing to scheduling issues.
But he said he believed the two sides had narrowed the items of difference, while the remaining issues were the hardest ones.
#rubio#munich#security#conference#europe
📱American Оbserver - Stay up to date on all important events
🇺🇸
👟 ¡Jueves de ofertones en moda y básicos para el hogar!
Hoy el día viene fuerte con unas zapatillas Munich G-3 a menos de la mitad de su precio (se quedan en 28,9€) y un pack de 2 camisetas BOSS por solo 13€. Para la casa, el mega pack de 100 pastillas Finish es un imprescindible para ahorrar en la compra mensual, junto con el práctico set de cuchillos Arcos. Además, destacamos los auriculares inalámbricos realme súper baratos y el pack doble de crema de manos Neutrogena para cuidarse por muy poco. 👕🍽️
🔥 Munich Zapatillas G-3 por 28,9€ (-53% dto)
🔗https://amzn.to/4lzlr9x
🔥 BOSS Pack 2Camisetas por 13€ (-45% dto)
🔗https://amzn.to/3NkyCyv
🔥 realme Buds Auriculares por 15,9€ (-36% dto)
🔗https://amzn.to/4bmeggo
🔥 Finish 100 Pastillas Lavavajillas por 14,9€ (-44% dto)
🔗https://amzn.to/4rxR3Od
🔥 Arcos Set Cuchillos Mondadores por 7,6€ (-23% dto)
🔗https://amzn.to/4dhmZTq
🔥 Neutrogena Pack 2 Crema de manos por 5,6€ (-52% dto)
🔗https://amzn.to/4uoZGNN
#Munich#BOSS#realme#OfertasAmazon#Ahorro
Dear passengers!
If you plan to travel to Munich, kindly note the following information. From February 4, 2023, the flight schedule on the Dushanbe-Munich-Dushanbe route is changing and operates on Saturdays departing at Dushanbe at 01:40 local time, and at Munich at 17:05 local time. The new schedule will create more flexibility for passengers, especially transit passengers, providing more opportunities for connecting flights.
✈️
Уважаемые пассажиры!
С 4 февраля 2023 года меняется расписание полётов по маршруту Душанбе-Мюнхен-Душанбе. Согласно новому расписанию рейсы будут выполняться по субботам. Вылет из Душанбе – в 01:40 по местному времени, из Мюнхена – в 17:05 по местному времени. Новое расписание создаст больше удобств для пассажиров, в особенности транзитных и даст им возможность выбора более удобных стыковочных рейсов.
#dushanbe#munich#душанбе#мюнхен
#Commentary: The #Munich Manifesto: Rubio’s recolonization blueprint, case for #African resistance
In this commentary, Mohammedawel Hagos offers a critical analysis of Marco Rubio's 2026 Munich Security Conference address, arguing that the speech reflects a broader Western agenda to revive colonial-era dominance over the Global South. Drawing on historical memory like #Ethiopia’s victory at the Battle of #Adwa, he warns that Africa faces “a renewed threat” of economic and political subjugation.
Rubio's address, he argues, is "a manifesto for recolonization" that sanitizes colonialism's violent legacy—evident in recent #US actions in #Venezuela and #Iran that "exemplify modern imperial coercion."
He calls on Global South nations to unite against this "21st-century corporate colonial project," cautioning that "history will not be kind to those who choose silence."
https://addisstandard.com/?p=56319
✈️ Munich — a city where tradition meets modernity! From majestic palaces to futuristic architecture and trendy neighborhoods — there's something for everyone here. 📍 Flying to Munich? Purchase your ticket on our website or in the mobile app.
✈️ Мюнхен — город, где традиции встречаются с современностью! От величественных дворцов до футуристической архитектуры и модных кварталов — здесь каждый найдет что-то по душе. 📍 Летим в Мюнхен? Приобретайте билет на нашем сайте или в мобильном приложении.
✈️ Мюнхен — шаҳрест, ки дар он анъанаҳо бо замонасозӣ вомехӯранд! Аз қасрҳои бошукӯҳ то меъмории футуристӣ ва маҳаллаҳои замонавӣ — ҳар кас дар ин ҷо чизе ба дил меёбад. 📍 Ба Мюнхен парвоз мекунем?
Чиптаи худро дар сомонаи расмӣ ё барномаи мобилӣ харидорӣ намоед.
#somonair#сомонэйр#мюнхен#munich#бавария