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

Резултати

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

Пребарај: #february2023

当前筛选 #february2023清除筛选
The Open Platform

@topco · Post #43 · 02.03.2023 г., 09:01

DeFi: February headlines - Liquid Staking Replaces DeFi Lending as Second-Largest Crypto Sector, the value of cryptocurrencies deposited in liquid staking protocols has increased to about $14 billion, trailing just deposits at decentralized exchanges (source), Lido saw a $240 million inflow in the form of 150,000 ether (ETH), "apparently from Justin Sun" (source) - G20 Financial Stability Board Report Flags DeFi 'Vulnerabilities', criticizing the niche's "actual degree of decentralization," the danger of crypto bridges, and bugs found in the smart contracts that underpin DeFi's applications (source) - Forsage Founders Indicted for $340M Ponzi Scheme Masquerading as DeFi Platform, company relied on smart contracts whose coding is consistent with a Ponzi scheme, the U.S. Justice Department says (source) - Solana-Based DeFi Protocol Everlend Announces Shut Down, the project highlighted a lack of liquidity and the overall shrinking of the borrowing and lending market as the causes of its demise (source) - DeFi Pioneer MakerDAO Announces Aave Competitor Spark Protocol, Spark Protocol will “amplify the features of MakerDAO by enabling a liquidity market for supplying and borrowing scalable crypto assets with variable and fixed rates” (source) - Several Leading DeFi Protocols Are Still Controlled by Whales, including Lido, GMX, Frax Finance, and Curve, which leads to the point that they are not decentralized, since VCs and whales can control governance (source) #February2023#DeFi#trends

The Open Platform

@topco · Post #47 · 08.03.2023 г., 09:01

Metaverse: February headlines - Meta Free Cash Surge Clears The Way For More Metaverse Investment: with support from better-than-expected performance across the family of apps, including Facebook breaking into 2 billion daily active users for the first time, the results are likely to limit investor objections to the company’s spending on developing its metaverse (source) - Tencent scraps plans for VR hardware as metaverse bet falters (source) - Pantera Invests $10M in Metaverse Game Worldwide Webb - the Web3 game allows players to use their existing NFT collections as avatars (source) - Colombia’s legal system experiments in the metaverse: a Colombian court recently hosted its first legal trial in the metaverse, with the court magistrate saying it felt “more real than a video call” (source) - Mitsubishi, Fujitsu and Other Tech Firms to Create ‘Japan Metaverse Economic Zone’, the goal of the metaverse alliance is to help build the framework for corporations to tap into Web3 marketing, work reform and consumer experience initiatives (source) #metaverse#February2023#trends

The Open Platform

@topco · Post #45 · 06.03.2023 г., 09:01

Payment Solutions: February headlines - Twitter's payment system prepares for potential crypto integration, Musk's Twitter payment vision is in tune with fiat-crypto gateway Alchemy Pay (source) - Visa Eyes High-Value USDC Settlement Payments on Ethereum, the company reportedly seeks to meet customer requests to convert digital assets into fiat payments, similar to how it converts foreign currencies (source) - Brazil’s Oldest Bank Takes a Leap into the Future with Crypto Tax Payment Options: Banco do Brasil will allow residents to pay their taxes with crypto (source) - UK Banks Blocking Crypto Access Given Fraud, Volatility, bank CEOs appeared more skeptical about the potential benefits of a central bank digital currency – the day after the Treasury and Bank of England said a digital pound was likely to be needed (source) #paymentsolutions#February2023#trends

The Open Platform

@topco · Post #46 · 07.03.2023 г., 09:02

Web3Creator Economy: February headlines - Maximizing Profits Will ‘Kill’ Web3: Animoca Brands Chairman: Yat Siu described royalties as the gas that keep an economy of creators humming, comparing it to the gas fees charged to process each transaction on Ethereum’s network (source) - NFT Royalties Are 'Not Going Away on SuperRare': Co-Founder Jon Perkins - this statement is a response to the OpenSea’s controversial move to change its creator royalty and fee structure earlier this month that has raised serious questions about what the value proposition of NFT marketplaces will be if artists and the original creators are cut off revenue streams (source) - New YouTube CEO Is Bullish on Web3 Tech Like NFTs and the Metaverse: Neal Mohan has said that NFTs could enable “creators to build deeper relationships with their fans” (sources) - The harsh reality fosters dissatisfaction with web2 platforms for creators: the average income for a full-time creator is less than $100,000, the median is $50,000; stiff competition and high costs meant only 4% of creators earn a living from content; 46% made less than $1,000 a year in 2022 (source) #creatoreconomy#February2023#trends

The Open Platform

@topco · Post #44 · 03.03.2023 г., 09:01

Wallets: February headlines - Algorand (ALGO)-Based Crypto Wallet MyAlgo Urges Users To Withdraw Assets After $9,600,000 Attack, Algorand Foundation CTO John Woods says about 25 wallets were affected by the attack (source) - Mastercard Rolls Out System Allowing for Stablecoin Payments Directly From Crypto Wallet, a collaboration between financial services giant Mastercard and web3 tech company Immersve is set to offer a new option for paying physical, digital and metaverse purchases using crypto assets (source) - Multicoin, Sequoia Lead $6M Round in Solana-based Crypto Wallet TipLink, Circle Ventures, Solana Ventures, and Paxos also participated in the round (source) - Addressable raises $7.5M to match crypto wallets to Twitter accounts, the solution allows marketers to promote games or conferences etc. to crypto wallet holders on Twitter, thus increasing the return on ad spend by targeting audiences that are more likely to buy products, and introducing higher efficacy/ROI (source) - Coinbase Adds New Wallet Security Features To Protect Against Phishing and Scams, including transaction previews, token approval alerts, and a new “enhanced layers of protection” (source) #February2023#wallets#trends