Когда разрабатываете свой 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
A light beige sphere rolling on the edge of an abstract golden arch, a giant pastel sphere, minimalist sculptural forms geometric objects composition, rendered in the style of Cinema4D, a light green background. Cinema4D rendering, close-up crop view, high resolution, macro photography, detailed textures --ar 2:3 --v 7
#sculpture
📣Midjourney prompts
A 3D fragment of rugged limestone floating in mid-air, covered with green moss, pale pink and orange corals, lichen, translucent quartz crystals, wildflowers with light blue petals, clean white background, soft warm natural lighting, photorealistic render, Octane Render, Cinema 4D --ar 3:4 --raw --v 7 --draft
by u4777486387
#sculpture
📣Midjourney prompts
A surreal collage of Plato and Aristotle floating in deep space, surrounded by glowing galaxies, cosmic nebulae, and celestial bodies. The background is an optical illusion of wavy black-and-white lines, blending into the cosmic void, creating a hypnotic, dreamlike atmosphere. A bold, glowing sun or planet in vibrant orange contrasts with the monochrome waves. Floating ancient Greek sculptures of Plato and Aristotle appear weightless, surrounded by philosophical symbols, sacred geometry, and ethereal cosmic dust. A mix of classical art, futuristic surrealism, and optical illusion, ultra-detailed, mesmerizing, and immersive --v 6.1 --ar 2:3 --s 50
by u8959768711
#sculpture
📣Midjourney prompts
an abstract shiny glimmering oblong metal goopy object floating in the middle of a dark sand dune with primary light focusing on the object --v 6.1
by formula1345
#sculpture
📣Midjourney prompts
Hyperrealistic photograph of a classical Greek marble statue with damaged smoothed face. The statue is positioned against a black background. The interplay of light highlights the texture of the statue and the damage give a dark gritty vibe --ar 4:5 --style raw --p vh9rjv1 --s 150 --v 6.1
by liamdomonkos
#sculpture
📣 Midjourney prompts
ea jar, Chinese style, divine phoenix decoration, hotel shelf, decoration, three-dimensional relief, white jade texture, transparent, elegant details --ar 1:2 --v 6.1
--
Sculptures with the theme Classic of Mountains and Rivers --ar 2:3 --v 6.1
by angus6930
#sculpture
📣 Midjourney prompts
Two large rocks in the shape of human heads, they look at each other and smile, a crescent moon between them, a dark blue sky, night photography, in the style of Aerial Photography, in the style of Wes Anderson, in the style of David LaChapelle, cinematic, shot on a film camera, Kodak film stock. --ar 105:128 --v 6.1
-
Two rock formations shaped like a woman's shoulders, a crescent moon in the dark blue night sky, in the style of Vincent Munier --ar 105:128 --v 6.1
by mr-indolent
#sculpture
📣 Midjourney prompts
A conceptual stack of stone building bricks, concrete and timber. It is set against a solid brown background to highlight the contrast between the diffeent objects and background. This art piece conveys creativity through geometric shapes and textured surfaces --v 6.1 --ar 57:85
by mr-indolent
#sculpture
📣 Midjourney prompts
thin sheet of glass monument standing upright in a black stone query. evening light reflecting from the glass onto the stones and creates rainbow like colors. the glass is about 50% of the image. in the style of a product art shooting --ar 3:4 --v 6.1
by timo_weiss
#sculpture
📣 Midjourney prompts
🧘Отдохнув от гаджетов и соцсетей, бесконечно понимаешь, сколько же в нашей жизни информационного и визуального мусора.
Минимализм во всём так прост и одновременно недосягаем.
an Majestic statue of Buddha, in the style of iris van herpen, franciszek starowieyski, peter holme iii, graceful movements, national geographic photo, caravaggesque chiaroscuro, landscapes in motion --c 20 --ar 3:4 --q 2 --style raw --sref 492309580 --p zww2nvy oiwf4m5 --s 1000 --v 6.1
by zhya666
#sculpture
📣 Midjourney prompts
A serene classical sculpture of a woman's head with closed eyes, adorned with soft, delicate pink flowers. The flowers gently float around her head, as if suspended in mid-air. The background is a minimalist light pastel blue, creating a dreamy, ethereal atmosphere. The entire scene should evoke a sense of calm, blending traditional art with modern aesthetics, featuring a balance between solid marble-like textures and the delicate, airy nature of flower petals --v 6.1
-
A beautiful woman Greek statue-like head, holding a rose in her hand, facing the camera, with her blonde hair in an updo, in the style of David LaChapelle and Mapplethorpe, a collage --v 6.1 --ar 7:8
by velskaa, cherryoasis
#sculpture
📣 Midjourney prompts