考虑以下示例代码:
from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QLabel, QWidget,
QMainWindow, QVBoxLayout, QTextEdit)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
cwidget = QWidget(self)
cwidget.setStyleSheet("QWidget { background-color: red; }")
self.setCentralWidget(cwidget)
self.resize(100, 100)
vbox = QVBoxLayout(cwidget)
vbox.addWidget(QTextEdit(self))
vbox.addWidget(BlackBar(self))
class BlackBar(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setStyleSheet("* { background-color: black; color: white; }")
hbox = QHBoxLayout(self)
hbox.setSpacing(5)
hbox.addWidget(QLabel(text="eggs"))
hbox.addWidget(QLabel(text="bacon"))
if __name__ == '__main__':
app = QApplication([])
main = MainWindow()
main.show()
app.exec_()
它有:
- QMainWindow,QWidget作为中央小部件(红色),QVBoxLayout作为中央小部件的子级。里面有: - QTextEdit(只是作为填充) - QWidget(黑色),其中包含QHBoxLayout。在那里: - 两个QLabel
它看起来像这样:
[图片]
我希望标签之间的空格是黑色的,因为QHBoxLayout是BlackBar的子级,但似乎BlackBar在其中只是“不可见”,而中央小部件“透过来了”。为什么会这样?