如何将PyQt6窗口标题字体设置为粗体?
解决PyQt6窗口标题无法加粗的问题
你的代码里调用window.setFont(font)只会设置窗口内部控件的字体,不会影响窗口标题——窗口标题的字体是由操作系统的窗口管理器控制的,Qt本身无法直接修改标题栏的字体样式(包括加粗)。如果要实现类似效果,有两种可行方案:
方案一:使用自定义标题栏
完全抛弃系统默认的标题栏,自己用Qt控件实现一个标题栏,这样就能完全控制标题的字体样式:
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QLabel from PyQt6.QtGui import QFont from PyQt6.QtCore import Qt class CustomTitleBar(QWidget): def __init__(self, parent=None): super().__init__(parent) layout = QHBoxLayout(self) layout.setContentsMargins(10, 5, 10, 5) # 标题标签,设置粗体 self.title_label = QLabel("MyPyQt6 App") title_font = QFont() title_font.setBold(True) title_font.setPointSize(12) self.title_label.setFont(title_font) self.title_label.setAlignment(Qt.AlignmentFlag.AlignCenter) layout.addWidget(self.title_label) self.setStyleSheet("background-color: #f0f0f0;") class MainWindow(QMainWindow): def __init__(self): super().__init__() # 隐藏系统标题栏 self.setWindowFlags(Qt.WindowType.FramelessWindowHint) # 设置自定义标题栏 title_bar = CustomTitleBar(self) self.setMenuWidget(title_bar) # 主内容区 central_widget = QWidget() central_widget.setStyleSheet("background-color: white;") self.setCentralWidget(central_widget) self.resize(400, 300) app = QApplication([]) window = MainWindow() window.show() app.exec()
方案二:使用HTML格式的标题(仅部分平台支持)
部分Qt支持的平台(比如Windows)允许在窗口标题中使用简单的HTML标签,你可以尝试这种方式:
from PyQt6.QtWidgets import QApplication, QMainWindow app = QApplication([]) window = QMainWindow() # 使用HTML的<b>标签设置粗体 window.setWindowTitle("<b>MyPyQt6 App</b>") window.show() app.exec()
注意:这种方法兼容性不好,不同操作系统或桌面环境的窗口管理器可能不支持HTML格式的标题,实际效果取决于平台。
内容的提问来源于stack exchange,提问作者mapperx
相关产品推荐
相关产品推荐

