TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #381 · 23 окт.

Установить свойства виджета в 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

Hashtags

Резултати

Пронајдени 33 слични објави

Пребарај: #mamdani

当前筛选 #mamdani清除筛选
Trump's Ear

@trumpsear_tg · Post #2202 · 27.02.2026 г., 15:04

New York Mayor Zahran Mamdani unexpectedly arrived at the White House for a meeting with Donald Trump #Trump#Mamdani 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #1825 · 25.11.2025 г., 18:01

Trump loves handsome and confident men very much. For example, Bill Clinton. No wonder Mamdani kept his hands in one place throughout the meeting. #Trump#Mamdani 👂More on Trump's Ear

Trump's Ear

@trumpsear_tg · Post #2037 · 21.01.2026 г., 19:59

Fox News is outraged that the new socialist mayor of New York, Zohran Mamdani, installed a bidet in his residence. The article did not specify which specific bidet was installed in the mayor's residence, but kindly noted that it could cost from 40 to 2000 dollars. #Mamdani#Media 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #1808 · 21.11.2025 г., 01:00

This person is part of President Trump's inner circle and influences his decision-making. Loomer quickly corrected the tweet when it was explained to her that the whole world uses Arabic numerals anyway. #Mamdani#GOP 👂More on Trump's Ear

Hashtags

Trump's Ear

@trumpsear_tg · Post #1891 · 10.12.2025 г., 19:05

The warnings were stark. If Zohran Mamdani were to win the New York City mayoral election, his plans to raise taxes – slightly – on the city’s wealthiest residents would cause millionaires to bolt en masse, decamping to lower-tax states such as Florida and Texas. #NY#Mamdani 👂More on Trump's Ear

Hashtags

Trump's Ear

@trumpsear_tg · Post #1769 · 12.11.2025 г., 15:05

Hochul opposed free buses, but is ready to support Mamdani's other ideas. New York Governor Kathy Hochul refused to support the idea of the new mayor of the city, Zohran Mamdani, to make bus travel free. At the Somos Puerto Rico conference in San Juan, she said she was not ready to "take money out of a system that survives by paying for travel." According to her, assistance can be sent to those who are unable to pay, but the payment cannot be completely canceled, writes abc7NY. Hochul says that canceling the payment will hit the MTA's budget and the stability of transportation. And Transport Minister Sean Duffy wrote on social media that "nothing is free" and called Mamdani's idea utopian. The mayor himself considers the victory a "mandate for change" and promised to fulfill all his election promises, including free buses. In addition, Mamdani wants to expand access to kindergartens. According to Hochul, the program will require about $15 billion, but she is ready to support it. #NY#Mamdani 👂More on Trump's Ear

Hashtags

Trump's Ear

@trumpsear_tg · Post #1743 · 06.11.2025 г., 14:12

🔥Mamdani presented his plan for the transformation of the city The new mayor of New York Zohran Mamdani promised to turn the metropolis into a "city accessible to all" 🗺 and has already presented the first points of his program. His plan involves large-scale social reforms, which critics call utopian, and supporters - a chance for a new era for New York. One of Mamdani's main initiatives is free public transport. 🚎 He wants to make all bus routes within the city free and expand the network of dedicated lanes. In addition, the mayor intends to introduce free kindergartens for families with children under five years of age and open city grocery stores with a minimum margin. 🛒 Economists warn that similar experiments in the United States have already failed: for example, in Kansas City, such stores have closed due to losses and thefts. Mamdani pays special attention to housing: he promised to freeze the growth of rental rates 🏠 and build a new "affordable" housing stock. The mayor plans to pay for all this by increasing taxes for the rich and large companies — by 2 percentage points for millionaires and up to 11.5% for businesses. 📊 Experts warn that such measures can scare off investors and lead to companies fleeing the city. In the field of security, Mamdani wants to reduce the role of the police ⚡️ and transfer some of its functions to social services. It will not be easy for the new mayor to implement an ambitious program, since for tax changes he needs the consent of the governor of the state, Kathy Hochul, who has already stated that she does not intend to raise taxes. #NY#Mamdani 👂More on Trump's Ear

Hashtags

Savino Balzano

@savinobalzano · Post #1203 · 05.11.2025 г., 11:55

https://x.com/SavinoBalzano/status/1986039391706353723?t=gAy-_lGAvfSxEYApv8mr-w&s=19 Desidero esprimere le mie congratulazioni alla sinistra italiana. Mi inchino dinanzi a tutti i sinistri d'Italia, a tutti i profili con la bandierina arcobaleno e l'emoticon del pugno chiuso. Desidero altresì congratularmi con tutti i nostri ecologisti: oggi ho letto messaggi di esultanza, assolutamente comprensibile, per il trionfo degli autobus elettrici. Socialismo ecosostenibile, nuove parole d'ordine. Insomma, rivolgo tutte le mie felicitazioni alla sinistrucola italiana per l'elezione di Zohran #Mamdani a sindaco di #NewYork. Traguardo davvero epocale, ma nessun indugio, mi raccomando: mai crogiolarsi sugli allori. Schlein, Fratoianni e Bonelli guardano già a Miami.

ПретходнаСтраница 1 од 3Следна