Home > Back-end >  How can I make it so that the background color and foreground color of a QLabel are different? (PyQt
How can I make it so that the background color and foreground color of a QLabel are different? (PyQt

Time:01-03

So I've been trying to look for a way to create a window that is fully black, and has dark red text in it. So I tried doing this below.

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
window = QMainWindow()
window.setFixedSize(800, 200)
window.setWindowFlag(Qt.FramelessWindowHint)
dark_red_text = QLabel(parent=window, text="Dark red text.")

dark_red_text.setFont(QFont("Times New Roman", 40))
dark_red_text.setStyleSheet("color: red;")
dark_red_text.adjustSize()
dark_red_text.move(260, 65) 
window.show()
app.exec()  

This gives me a window with a white background and red text in it. But I wanted a black background, so I tried adding these lines:

black_background = QLabel(parent=window)
black_background.setStyleSheet("background-color: black;")
window.setCentralWidget(black_background)

The out put was just a black window with nothing on it. How can I solve this problem so that I get the window I want?

CodePudding user response:

Note that when you add the 'black_background' Qlabel, you are just creating a new label that will be placed over the 'dark_red_text', so this one gets hidden. A possible solution is to set the background color on the window and the text color on the 'dark_red_text' Qlabel. The 'dark_red_text' will, by default, inherit the background color of the parent widget, which in this case is 'window'.

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
window = QMainWindow()
window.setFixedSize(800, 200)
window.setWindowFlag(Qt.FramelessWindowHint)
window.setStyleSheet("background-color: black")
dark_red_text = QLabel(parent=window, text="Dark red text.")
dark_red_text.setFont(QFont("Times New Roman", 40))
dark_red_text.setStyleSheet("color: red")
dark_red_text.adjustSize()
dark_red_text.move(260, 65) 
window.show()
app.exec() 
  • Related