简体   繁体   中英

How can I make it so that the background color and foreground color of a QLabel are different? (PyQt5)

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?

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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM