Changing the background color of a widget


https://forum.reallusion.com/Topic403624.aspx
Print Topic | Close Window

By RobertoColombo - 5 Years Ago
HI,

I am trying, with no luck, to change teh background color of a widget.
The code apparenly should be easy: for example, here given I create a label and try to set the background to RED, but nothing happens.
Basically I am following the method described here: https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget
I tried also with QPalette.Background for setColor() (this value is anyway considered obsolete in QT doc) but still no change in color.

import PySide2, RLPy
from PySide2 import *
from PySide2.shiboken2 import wrapInstance

#-- Make a global variable contain dialog --#
sample_dialog = None

def run_script():

    global sample_dialog

    sample_dialog = RLPy.RUi.CreateRDialog()
    sample_dialog.SetWindowTitle("Sample Dialog")

    #-- Create Pyside layout for RDialog --#
    pyside_dialog = wrapInstance(int(sample_dialog.GetWindow()), PySide2.QtWidgets.QDialog)
    pyside_dialog.setFixedWidth(200)
    sample_layout = pyside_dialog.layout()
 
    #-- Create the Label --#
    label = PySide2.QtWidgets.QLabel("Test")

    #-- Set the widget color --#
    pal = PySide2.QtGui.QPalette()

    color_red = PySide2.QtGui.QColor('red')
    label.setAutoFillBackground(True)
    pal.setColor(PySide2.QtGui.QPalette.Window, color_red)
    label.setPalette(pal)

    #-- Add Label --#
    sample_layout.addWidget(label)

    sample_dialog.Show()    
    
Any ideas ?

Thanks

  Roberto
By RobertoColombo - 5 Years Ago
Solved!

It works if the style sheet is used rather than a QPalette.
This code makes its job (RGB values are just an example):

import PySide2, RLPy
from PySide2 import *
from PySide2.shiboken2 import wrapInstance

#-- Make a global variable contain dialog --#
sample_dialog = None

def run_script():

    global sample_dialog

    sample_dialog = RLPy.RUi.CreateRDialog()
    sample_dialog.SetWindowTitle("Sample Dialog")

    #-- Create Pyside layout for RDialog --#
    pyside_dialog = wrapInstance(int(sample_dialog.GetWindow()), PySide2.QtWidgets.QDialog)
    pyside_dialog.setFixedWidth(200)
    sample_layout = pyside_dialog.layout()
 
    #-- Create the Label --#
    label = PySide2.QtWidgets.QLabel("Test")
    
    col = PySide2.QtGui.QColor(111, 100, 8)
    label.setStyleSheet("QWidget { background-color: %s }" % col.name()) 

    #-- Add Label --#
    sample_layout.addWidget(label)

    sample_dialog.Show()    

By SeanMac - 5 Years Ago
That is a fast answer to your problem, Roberto.

I hope you will thank Roberto very much for his assistance;-)