PyQt styling with QSS & #pyqtProperty - css

As a simple example, suppose I have a QPushButton that has some basic styling applied to it using button.setStyleSheet(). Additionally, I want some parts of the style (background color) to change in response to events triggered by the user.
I could simply make calls to button.setStyleSheet() throughout my code, but these will erase pre-existing style attributes. So I would not be able to edit just one styling attribute in response to some signal, rather I would have to specify all style attributes every time the style changes (even if only one or a few style attributes are actually being modified).
I understand this can be done more neatly with the QSS property selector which can apparently be used with "any Qt property that supports QVariant::toString()". This is also described for C++ here: dynamic properties & stylesheets.
So suppose I have a custom widget class, and I want some of its styling to depend (responsively) on a property of my custom class, e.g. a state property. It sounds like I should be able to do something like
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import pyqtProperty
class StatefulWidget(QPushButton):
""" QPushButton colored to reflect its state. """
def __init__(self, state=0):
super().__init__()
self.state = state
self.setStyleSheet('''
StatefulWidget[state=0] {
background-color: red;
}
StatefulWidget[state=1] {
background-color: green;
}
''')
#pyqtProperty(int)
def state(self):
return self._state
#state.setter
def state(self, state):
# Register change of state
self._state = state
# Update displayed style
self.style().polish(self)
but this does not work for me.
Can anyone suggest the proper way to make this work? The intended behavior is that the style should be updated whenever the property changes, but the underlying CSS/QSS should be fixed.
Related:
Update stylesheet without losing original style

The documentation about the QSS property selector says:
You may use this selector to test for any Qt property that supports QVariant::toString()
The QSS parser code is quite complex and somehow cryptic, and I've never been able to completely follow its logic, but I believe that it always tries to convert string values to numbers whenever they contain digits, so the 0 value for the QSS property selector will not match the "0" resulting from toString().
As a general rule, always use quotes around values:
self.setStyleSheet('''
StatefulWidget[state="0"] {
background-color: red;
}
StatefulWidget[state="1"] {
background-color: green;
}
''')

Related

Qt stylesheet selector using enumed properties

I'm trying to set different visual styles for a pressed QToolButton depending on whether it displays a menu or not.
In my code, tool buttons having menu set their popupMode property to QToolButton::InstantPopup (value 2), while buttons without an associated menu keep the default value (QToolButton::DelayedPopup, value 0).
I tried to use such property in different ways as selector, but only the last one (QToolButton[popupMode="2"]) worked:
/* Not working */
QToolButton[popupMode=InstantPopup]:pressed,
QToolButton[popupMode="InstantPopup"]:pressed,
QToolButton[popupMode="QToolButton::InstantPopup"]:pressed,
QToolButton[popupMode="QToolButton--InstantPopup"]:pressed,
QToolButton[qproperty-popupMode=InstantPopup]:pressed,
QToolButton[qproperty-popupMode="InstantPopup"]:pressed,
QToolButton[qproperty-popupMode="QToolButton::InstantPopup"]:pressed,
QToolButton[qproperty-popupMode="QToolButton--InstantPopup"]:pressed,
QToolButton[qproperty-popupMode="2"]:pressed
{
background-color: blue;
}
/* Working */
QToolButton[popupMode="2"]:pressed,
{
background-color: red;
}
(This is a compilation of the options, I've tested them separately).
Documentation mentions that if the enum is declared using Q_ENUM (as ToolButtonPopupMode does), then it should be referenced by name, not by value, but, as it can be seen above, it seems it is not the case for selectors.
Question: Would it be possible to use such enum's name as selector in the stylesheet instead of the enum's value?
Note: I understand that other options such as custom properties with a more expressive, Qt-independant value can make the work too. I'm curious about the possibility of using the enum in the described way.
QToolButton[popupMode=InstantPopup]:pressed is the correct one.
setProperty(<property_name>, QVariant::fromValue(<enum_value>)) for enum class.
setProperty(<property_name>, <enum_value>) for enum.
But you need to reload the style if you want it to change dynamically.
Read about QStyle::unpolish and QStyle::polish.

Adding new stylesheet parameters for custom Qt widgets

I would like to add stylesheet options for a custom widget I have developed. We have extended the QPushButton to be a different colour and to flash when it is depressed. This has been done by adding a new property, background color down. And we set this in code. But I would like to set this instead using a Qt stylesheet entry, something like
QFlashingButton
{
background-color-down: yellow;
flashing-interval: 5;
}
I can see one way to do this, read out the stylesheet info using the stylesheet() method, then parse it for parameters relevant to my widget and set them. But I am wondering if there is some way to access the code Qt have themselves for processing stylesheets. At first sight of their code this seems perhaps not to be publically available.
As long as the parameter you want to control in the stylesheet is a QProperty, you can set it in the stylesheet using the syntax: qproperty-<PROPERTY_NAME>: <PROPERTY_VALUE>
I don't think property names can actually have dashes in them, so assuming your QProperties on your custom widget are actually backgroundColorDown and flashingInterval, then your stylesheet would look like:
QFlashingButton
{
qproperty-backgroundColorDown: yellow;
qproperty-flashingInterval: 5;
}

Styling QML without manually marking each property to be styled

I know that QML does not support CSS styling like widgets do, and I have read up on alternative approaches to styling/theming:
https://qt-project.org/wiki/QmlStyling
http://www.slideshare.net/BurkhardStubert/practical-qml-key-navigation/34
Common for these approaches is that they require the developer to specify the parts of the QML that can be styled, either by binding to a property in a “styling QML file/singleton”, or by using a Loader to load a different QML component based on style name. What I would like is something that works like the "id" selector in CSS instead of the "class" selector, so that the individual QML files do not have to know whether they will be styled later on or not.
My current approach make all the QML files look similar to this (using approach in link 2):
Main.qml
Rectangle {
Id: background
color: g_theme.background.color
//g_theme is defined in root context and loaded dynamically
}
What I would like to do is:
Main.qml
Rectangle {
Id: background
color: “green” // default color
}
And then have a styling file that defines (or similar)
Main.qml #background.color: red
Is this possible at the moment, or something that is in the pipeline for a future Qt version, or will the preferred way of styling continue to be something similar to the approach described in the links above?
The preferred way isn't applying a style on default components, but deriving from these components to create pre-styled custom components.
What I do for my projects :
First, I create one centralized 'theme' file, as a JavaScript shared module :
// MyTheme.js
.pragma library;
var bgColor = "steelblue";
var fgColor = "darkred";
var lineSize = 2;
var roundness = 6;
Next, I create custom components that rely on it :
// MyRoundedRect.qml
import QtQuick 2.0;
import "MyTheme.js" as Theme;
Rectangle {
color: Theme.bgColor;
border {
width: Theme.lineSize;
color: Theme.fgColor;
}
radius: Theme.roundness;
}
Then, I can use my pre-styled component everywhere with a single line of code :
MyRoundedRect { }
And this method has a huge advantage : it's really object-oriented, not simple skinning.
If you want you can even add nested objects in your custom component, like text, image, shadow, etc... or even some UI logic, like color-change on mouse hover.
PS : yeah one can use QML singleton instead of JS module, but it requires extra qmldir file and is supported only from Qt 5.2, which can be limiting. And obviously, a C++ QObject inside a context property would also work (e.g. if you want to load skin properties from a file on the disk...).
It could also be helpful to look at Qt Quick Controls Styles
When using Controls Styles it is not necessary to explicitly assign each property in the target control. All properties can be defined in a separate [ControlName]Style component (e.g. ButtonStyle).
Then in target component (e.g. Button) you can just reference to style component in one line of code.
The only one downside here is that Style components are available for Qt Quick Controls only. Not for any Qt Component.

Get variable name of Qt Widget (for use in Stylesheet)?

In my application, a User clicks on any widget of my program (which are at the time; dormant) and picks a color for it.
This color will then be added to a stylesheet for that particular widget.
However, when the program ends and is started again, I would like that particular widget to retain its stylesheet.
I would like to not have to hard code in stylesheets for every widget. In fact, I'd rather not even know which particular widget is having the stylesheet.
What I'd really like to do is have a single style sheet for the application, and code the new color just to the particular widget clicked.
(ie: If the User clicked on a QPushButton and chose a stylesheet of { color: red},
I would like just THAT QPushButton red and none others.
So, if that QPushButton had a variable name of 'Clicky',
to the QApplications stylesheet I would add:
'QPushButton#Clicky { color: red }' )
To do this and not have to hard-code it in for every widget,
I must somehow convert the variable name of my PyQt4 widgets to strings.
How can I do this?
Thanks!
(I've read it can be extremely difficult to get python variable names from their values;
Is there any other form of ID for a widget that can be added to a stylesheet?)
PyQt4
python 2.7.2
Windows 7
You need to first setObjectName("somename") before an object is named, then objectName() will work, or even better - findChild(), or findChildren()
Example
header:
QButton foo;
class:
foo = new QButton();
foo.setObjectName("MySuperButton");
Then, finally in your QSS..
#MySuperButton {
background: black;
}
This also works similarly to CSS with
QButton#MySuperButton {
background: red;
}
The logic behind why you'd want to set multiple object names similarly (for different objects), or use the granularity of only one type of widget with a specific name is also pretty much the same as CSS.

Qt: Background color on QStandardItem using StyleSheet

I have a class that inherits QStandardItem and I put the elements in a QTreeWidget. The class receives notifications from the outside and I want to change the background color of the item based on what happened.
If I do not use stylesheets, it works just fine, like this:
void myClass::onExternalEvent()
{
setBackground(0, QColor(255,0,0)));
}
However, as soon as I put a stylesheet on the QTreeWidget, this has no effect : the stylesheet seems to override the setBackground() call.
So I tried :
void myClass::onExternalEvent()
{
this->setStyleSheet("background-color: red");
}
but this is probably all wrong, it changed the color of some other element on my screen, not sure why.
Does anyone have an idea on how I can alter the background color like with setBackgroundColor but still be able to use stylesheet on my QTreeWidget?
Palettes propagate to the children of a widget, and it's bad to mix and match style-sheet controls and native controls (I do not have a citation for the latter handy, but I have read it in the QT docs somewhere).
That being said, try setting setAutoFillBackground(false) on your QStandardItem derived class.
EDIT: Sorry - also, are you specifying the QTreeWidget in the stylesheet or just setting "background-color:"? If you specify the QTreeWidget only in the stylesheet that might take care of it as well.
QTreeWidget { background-color: white; }
But I think you still have to set the autoFillBackground(false).

Resources