简体   繁体   English

如何使 QLabel 的背景颜色和前景色不同? (PyQt5)

[英]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.所以我一直在尝试寻找一种方法来创建一个全黑的 window,其中包含深红色文本。 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.这给了我一个带有白色背景和红色文本的 window。 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.输出只是一个黑色的 window,上面什么都没有。 How can I solve this problem so that I get the window I want?我该如何解决这个问题,以便获得我想要的 window?

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.请注意,当您添加 'black_background' Qlabel 时,您只是创建了一个新的 label,它将放置在 'dark_red_text' 上,所以这个被隐藏了。 A possible solution is to set the background color on the window and the text color on the 'dark_red_text' Qlabel.一种可能的解决方案是在 window 上设置背景颜色,在“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'.默认情况下,“dark_red_text”将继承父窗口小部件的背景颜色,在本例中为“窗口”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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