7

I am quite new to PyQt. Does anyone tell me how to get the background color of a button or label (QPushButton, QLabel) in PyQt.

Linh Nguyen
  • 925
  • 1
  • 10
  • 23

3 Answers3

8

Here is a sample code. This will help you.

QPushButton button1, button2;
button1.setStyleSheet("background-color:#ff0000;");

//To get Background color
QColor color = button1.palette().button().color();

//To set fetched color
button2.setStyleSheet("background-color:" + color.name() +";");
AB Bolim
  • 1,997
  • 2
  • 23
  • 47
2

I haven't used PyQt, but I think API should be very similar to C++. To get background color of QWidget-based class, first get its palette and then call QPalette::color() with QPalette::Window role.

Oleg Shparber
  • 2,732
  • 1
  • 18
  • 19
2

This worked for me

from PyQt5.QtWidgets import QApplication, QLabel, QWidget
import sys

app = QApplication(sys.argv)
window = QWidget()
window.show()

myLabel = QLabel()
colorOfmyLabel = myLabel.palette().window().color().name()
print(colorOfmyLabel)

sys.exit(app.exec_())

the output:

#f0f0f0
Murat Demir
  • 716
  • 7
  • 26
Timo
  • 31
  • 5