Когда разрабатываете свой GUI с помощью PyQt для какого-либо софта бывает необходимо позаимствовать цвета из текущего стиля интерфейса. Например, чтобы правильно раскрасить свои виджеты, подогнав их по цвету. Ведь бывает, что ваш GUI используется в разных софтах. Причём некоторые со светлой темой а другие с тёмной.
По умолчанию стили наследуются, но если вы задаёте какую-либо раскраску для части виджета через свой styleSheet, то требуется ссылаться на цвета текущего стиля.
Как это сделать? Как получить нужный цвет из палитры имеющегося стиля? Это достаточно просто, нужно использовать класс QPalette и его роли.
Например, мне нужно достать цвет текста из одного виджета и применить его в другом как цвет фона (не важно зачем именно так, просто захотелось😊).
Получаем палитру виджета и сразу достаём нужный цвет, указав его роль.
from PySide2.QtGui import QPalette
color = main_window.palette().color(QPalette.Text)
теперь можем использовать этот цвет в стилях
my_widget.setStyleSheet(f'background-color: {color.name()};')
Готово, мы динамически переопределили дефолтный стиль используя текущий стиль окна!
На самом деле есть запись покороче, в одну строку и без лишних переменных. Не очень-то по правилам CSS, но Qt это понимает.
my_widget.setStyleSheet('background-color: palette(Text);')
Этот способ не подходит если вам нужно как-то модифицировать цвет перед применением в своих стилях. В этом случае потребуется первый способ.
Зато он прекрасно сработает в файле .qss, то есть не придётся в коде прописывать раскраску отдельных элементов через ссылки на палитру, всё красиво сохранится в отдельном файле .qss!
QListView#my_widget::item:selected {
background: palette(Midlight);
}
Про имеющиеся роли можно почитать здесь🌍
#qt#tricks
Лето в разгаре, и мы решили:
Почему бы не раздать то, что вы любите больше всего?
FRHT #GIVEAWAY
Разыгрываем 10 футболок из новой коллекции FRHT 🔥
Условие участия простое — Подписаться на этот канал 🏁
*если ещё не с нами
Мы случайным образом выберем 10 победителей и отправим выбранные футболки
Итоги 25 июля. Поехали 🚀
🎉Bitget Wallet x All At Once #Giveaway🎉
🕙Event duration: August 23 - August 30, 2024
💰Rewards:
🚀$3,000 worth of TON for 300 lucky participants🚀
5M xAAO prize pool is shared equally among all participants
How to join:
1️⃣ Follow @BitgetWallet + @AAO_Game
2️⃣ Join the AAO & Bitget Wallet Telegram groups:
3️⃣ Join the All At Once Bot and complete one game battle
4️⃣ Fill out the Google form to receive your reward
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
💝GAMEWTB Valentine's Day Giveaway - Steam Gift Card💝
Happy Valentine’s Day!💖 As a token of our appreciation for your continued support, the GAMEWTB TEAM has prepared a special gift🎁 for you.
💸Prize: $5 Steam Gift Card
📅FROM NOW - FEB 17, 2025
=How to Participate=
📲Follow our X: x.com/PC_Gamewtb
❤️♻️LIKE & RETWEET THIS POST☝️
⏰Winner will be announced on Feb 17th
✅COMMENT "DONE" UNDER THIS POST☝️
👀Wait our DM💌
Limited Time Event – Don’t Miss Out!
🤩Whether you're spending Valentine’s Day solo or with a special someone, remember to love yourself! GAMEWTB will keep bringing you the latest game news and exciting events.
Join Gamewtb Group for GIVEAWAYS!
#GIVEAWAY
💚🍀🌱 FARMERS, LISTEN UP! 💎✨
One of the LAST chances to grab OG role 🎖 and it’s about to go CRAZY 😤🔥
We're dropping a massive GIVEAWAY 🎁 /w 30 winners
EACH GETS 0.1 SOL 🤑 + OG 👑
How to join:
1. Join our X (Twitter)
https://x.com/ggpweb3
2. Join our Discord
https://discord.gg/gg-paradise
3. Leave wallet in #giveaway channel
4. Stay active on server
Results in Friday 🕶
Let’s make it loud before the farm goes wild 🌿🚀
💥500 QUACK AI NFTs and 200,000 QUACK Points Giveaway to TokenPocket users!
👉https://app.galxe.com/quest/TokenPocket/GC6YCtmDkS
🍾500 lucky winners will each receive a QUACK AI NFT!
🎯 Winners will also be eligible to earn an extra 400 points by interacting with the QUACK AI platform.
#giveaway
💧Airdrop : Lifestory💧
📣Complete Task: ➕ $6000 #Giveaway - 4 Days contest
🏆Winners: For All Valid Users
📅End date: After 4 Days
💎Ratings: ⭐️⭐️⭐️
🔛Galaxy Airdrop Gleam Click Here🔛
🌀 Follow on Twitter and retweet the pinned post.
🌀 After Done Airdrop Task then Create your wallet.
📡Enter your information to the Airdrop Gleam.
🗞Note: All airdrop steps should be completed.
⛵️Business Inquiry: Admin || Admin2
💥Big Congrats!
🏆Check if you are on the ZoomManor #Giveaway Winner List!
👉https://docs.google.com/spreadsheets/d/1QQ1rdc3jnt6BAhWL_8qhJJe56KyxSqF8BvCk21dLvSk/edit#gid=0
🎁The rewards will be distributed by ZoomManor before Jan 5th. ZoomManor
💙Thank you all very much for your participation!
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
🪂New airdrop: FOBOCLUB x MEXCGlobal Collab Event #giveaway
💰Reward: 50 FOBO CLUB WLs (NFT)
📅Distribution: uncertain
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🪂Airdrop: Mystery Box #Giveaway
💰Reward: $3,000
👨💼 Winner: All participants
📅 TIME:10/03/2022 07:00 AM - 10/09/2022 11:00 PM UTC
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!