How to customize the title bar in PyQt5?
To customize the title bar of PyQt5, you need to create a custom title bar area within a QWidget (or its subclasses) and add the desired widgets on it. Here is a simple example:
from PyQt5 import QtCore, QtGui, QtWidgets
class CustomTitleBar(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.setFixedHeight(30) # 设置标题栏高度
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0) # 设置边距为0
# 创建标题栏的小部件
self.title = QtWidgets.QLabel("Custom Title Bar")
self.minimize_button = QtWidgets.QPushButton("-")
self.maximize_button = QtWidgets.QPushButton("□")
self.close_button = QtWidgets.QPushButton("✕")
# 添加小部件到布局
layout.addWidget(self.title)
layout.addWidget(self.minimize_button)
layout.addWidget(self.maximize_button)
layout.addWidget(self.close_button)
# 添加样式
self.setStyleSheet("""
background-color: #333;
color: #fff;
font-size: 12px;
padding-left: 5px;
""")
# 连接按钮的信号与槽
self.minimize_button.clicked.connect(self.parent().showMinimized)
self.maximize_button.clicked.connect(self.toggleMaximize)
self.close_button.clicked.connect(self.parent().close)
def toggleMaximize(self):
if self.maximize_button.text() == "□":
self.parent().showNormal()
self.maximize_button.setText("▢")
else:
self.parent().showMaximized()
self.maximize_button.setText("□")
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Custom Title Bar Example")
self.title_bar = CustomTitleBar(self)
self.setMenuWidget(self.title_bar)
self.setContentsMargins(0, self.title_bar.height(), 0, 0) # 设置内容边距
# 添加内容部件
central_widget = QtWidgets.QWidget(self)
self.setCentralWidget(central_widget)
layout = QtWidgets.QHBoxLayout(central_widget)
label = QtWidgets.QLabel("Custom Window Content")
layout.addWidget(label)
self.setStyleSheet("""
QWidget {
background-color: #eee;
}
""")
if __name__ == "__main__":
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
In this example, we initially create a custom class called CustomTitleBar that inherits from QWidget and displays the title bar widgets (title, minimize button, maximize/restore button, and close button) in a horizontal layout. We also set some styles for the title bar.
Next, we will create a MainWindow class that inherits from QMainWindow. In its constructor, we will create an instance of CustomTitleBar and set it as the menu widget. We will also ensure that the content is not overlapped by the title bar by setting the margin of the content widget.
Finally, we created an application instance and displayed the main window.
Please note that this example only demonstrates the basic appearance and behavior customization of the title bar. You can modify and expand it according to your own needs.