import sys
from PySide6.QtCore import Qt, QPoint
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFrame
class CustomTitleBar(QFrame):
def __init__(self, parent=None):
super(CustomTitleBar, self).__init__(parent)
self.setStyleSheet("background-color: #2d2d2d")
self.setFixedHeight(30)
self.parent = parent
self.old_pos = None
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.titleLabel = QLabel("Custom Title Bar")
self.titleLabel.setStyleSheet("color: white")
layout.addWidget(self.titleLabel, alignment=Qt.AlignLeft)
self.minimizeButton = QPushButton("-")
self.minimizeButton.clicked.connect(self.parent.showMinimized)
layout.addWidget(self.minimizeButton, alignment=Qt.AlignRight)
self.maximizeButton = QPushButton("+")
self.maximizeButton.clicked.connect(self.toggleMaximizeRestore)
layout.addWidget(self.maximizeButton, alignment=Qt.AlignRight)
self.closeButton = QPushButton("x")
self.closeButton.clicked.connect(self.parent.close)
layout.addWidget(self.closeButton, alignment=Qt.AlignRight)
self.setLayout(layout)
def toggleMaximizeRestore(self):
if self.parent.isMaximized():
self.parent.showNormal()
else:
self.parent.showMaximized()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.old_pos = event.globalPos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton and self.old_pos is not None:
delta = event.globalPos() - self.old_pos
self.parent.move(self.parent.x() + delta.x(), self.parent.y() + delta.y())
self.old_pos = event.globalPos()
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
self.toggleMaximizeRestore()
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(Qt.FramelessWindowHint)
layout = QVBoxLayout()
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
self.title_bar = CustomTitleBar(self)
layout.addWidget(self.title_bar)
content = QLabel("This is a custom window with a custom title bar.")
layout.addWidget(content)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
运行效果图如下: