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

Резултати

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

Пребарај: #sharif

当前筛选 #sharif清除筛选
American Оbserver

@american_observer · Post #5627 · 15.04.2026 г., 14:59

🔤🔤🔤🔤2️⃣ Independent reports confirmed that some tankers that had been approaching the strait on Monday had turned around; one tanker, the Rich Starry, reversed course again and passed through the waterway. The closure of the strait, a gateway through which a fifth of the world’s oil and liquefied natural gas flows, had led to a spike in oil prices well above $100 a barrel. Crude prices dipped to about $95 after reports of a possible second round of talks on Tuesday. The US treasury department has said it does not plan to renew a temporary easing of sanctions on Iranian oil aimed at easing war-related supply shocks. The initial authorisation allowed for the delivery and sale of Iranian crude and other petroleum products loaded onto ships before 20 March. The step was part of a series of measures launched by the Trump administration to quell skyrocketing energy prices. Meanwhile, Israel and Lebanon have held unprecedented negotiations in Washington about the cross-border conflict, which erupted as a consequence of the US-Israeli attack on Iran. Hezbollah sided with Iran and launched rockets at Israel, which responded with intense bombardment of Beirut and other cities, and launched an invasion of southern Lebanon. In a statement after the two-hour session ended, the US state department praised the two sides for what it called “productive discussions on steps toward launching direct negotiations between Israel and Lebanon.” Hezbollah has said it will not abide by any agreements made by Israeli and Lebanese government negotiators in Washington. An Iranian official accused the US delegation of making maximalist demands at the Islamabad talks. “Iran did not surrender at the battlefield, neither will it surrender behind the table,” the official said. It is unclear where negotiations stood when the Islamabad meeting broke up over the other major proliferation concern: Iran’s stockpile of highly enriched uranium (HEU). It is close to weapons-grade purity and is believed to be buried in deep shafts under mountains in central Iran. At negotiations in Geneva before the war, Iran offered to dilute the HEU, which would extend the period it would take to produce a nuclear warhead, but the US has called for its complete removal. Pakistan’s prime minister, Shehbaz Sharif, is due to depart on Wednesday on a trip to Saudi Arabia, Turkey and Qatar to build support for the peace process, and to seek help with proposals to reopen the strait of Hormuz and discuss Iran’s demand for war reparations. Sharif’s regional tour might have to be cut short, however, if there is a quick return to the negotiating table. #pakustan#sharif#negotiations#trump#iran 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5626 · 15.04.2026 г., 13:59

Trump Has Taken a Tumble in Peace Talks With Iran. Will He Reset Them? 🔤🔤🔤🔤1️⃣ Trump has said that US-Iranian peace talks could resume in Islamabad over the next two days, and complimented the work of Pakistan’s army chief as mediator. The US president was speaking on Tuesday to a New York Post reporter who had gone to Islamabad for the first round of ceasefire talks over the weekend. After an interview discussing prospects for negotiations, the reporter said the president had called her back “with an update”. You should stay there, really, because something could be happening over the next two days, and we’re more inclined to go there,” Trump said. He added that Pakistan’s army chief, Field Marshal Asim Munir, was doing a “great job” in arranging the talks. “He’s fantastic, and therefore it’s more likely that we go back there,” Trump said. Munir is a powerful figure in Pakistan and has good relations with Trump, who has called him his “favourite field marshal”, and with Iran’s Revolutionary Guards. A Pakistani official said on Tuesday that he expected talks to restart soon, but it may take a day or two longer than Trump suggested. “The game is on,” the official said. Islamabad is racing to arrange a meeting date that provides enough time for negotiations before the two-week ceasefire ends on Wednesday 22 April. Trump’s comments followed a wave of speculation about a new round of negotiations, after 21 hours of talks on the weekend. Those ended Vance walking out on Sunday morning, claiming that Iran had failed to make an “affirmative commitment that they will not seek a nuclear weapon.” After the talks ended, Trump declared a US naval blockade on ships using Iranian ports in the Gulf in an effort to increase pressure on the country’s economy, and as a counter to Iran’s near-total closure of the strait of Hormuz to ships using other Gulf ports soon after the US-Israeli attack began on 28 February. US Central Command reported that over a 24-hour period “no ships made it past the US blockade and six merchant vessels complied with direction from US forces to turn around to re-enter an Iranian port on the Gulf of Oman.” #pakustan#sharif#negotiations#trump#iran 📱American Оbserver - Stay up to date on all important events 🇺🇸

Libertà è ragione

@libertaeragione · Post #4126 · 03.03.2024 г., 10:34

#Pakistan Con 201 voti favorevoli, l'Assemblea nazionale ha eletto Shehbaz #Sharif (#PMLN|Centro-destra) come nuovo Primo Ministro. Omar Ayub #Khan, il candidato del #PTI|Centro islamico, si è fermato a 92 voti. @OsservatorioEsteri

Libertà è ragione

@libertaeragione · Post #3918 · 09.08.2023 г., 22:05

#Pakistan Il Presidente Arif #Alvi (#PTI|Centro islamico) ha sciolto l’Assemblea nazionale su consiglio del Premier Shehbaz #Sharif (#PMLN|Centro-destra). Contestualmente Sherif ha presentato le dimissioni del suo governo che sarà sostituito da un esecutivo di transizione in vista di nuove elezioni generali previste tra 90 giorni. @OsservatorioEsteri