我尝试了你的代码,我可以重现同样的问题,对我来说这似乎是一个bug。
以下是使用自定义小部件作为标题的可能解决方法:
from PyQt5.QtWidgets import QLabel
CSS = """
#CustomTitle {
background-color: lightblue;
border: 1px solid black;
}
#CustomTitle:hover {
background: red;
}
QMainWindow::separator {
background: palette(Midlight);
}
QMainWindow::separator:hover {
background: palette(Mid);
}
"""
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QSize
class CenteredLabel(QtWidgets.QWidget):
def __init__(self, text, parent=None):
super().__init__(parent=parent)
self.verLayout = QtWidgets.QVBoxLayout()
self.setLayout(self.verLayout)
self.horLayout = QtWidgets.QHBoxLayout()
self.verLayout.addLayout(self.horLayout)
self.label = QtWidgets.QLabel(text)
self.horLayout.addWidget(self.label)
def sizeHint(self):
return QSize(300, 400)
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setCentralWidget(CenteredLabel("Central Widget"))
self.dockWidget = QtWidgets.QDockWidget(parent=self)
self.dockWidget.setWidget(CenteredLabel("Dock Widget"))
self.customTitle = QLabel("Dock Title", parent=self.dockWidget)
self.customTitle.setObjectName("CustomTitle")
self.dockWidget.setTitleBarWidget(self.customTitle)
self.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget)
def main():
app = QtWidgets.QApplication([])
# Fusion style is the default style on Linux
app.setStyle(QtWidgets.QStyleFactory.create("fusion"))
app.setStyleSheet(CSS)
win = MyWindow()
win.show()
win.raise_()