You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在QMenuBar、QToolBar左侧及QMainWindow左上角添加图标?

在QMainWindow左上角添加图标的实现方案

方法一:设置原生窗口标题栏图标

这是最常用的方式,直接给QMainWindow设置窗口图标,系统会自动在标题栏左上角显示:

代码示例(PyQt5/PyQt6)

from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QIcon
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 加载并设置窗口图标
        self.setWindowIcon(QIcon("your_icon_path.png"))
        # 初始化你的菜单栏、工具栏等界面元素
        self.init_interface()

    def init_interface(self):
        # 这里添加左侧菜单栏、上下工具栏的初始化代码
        self.setWindowTitle("示例窗口")
        self.setGeometry(300, 300, 800, 600)
        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

如果使用PyQt6,只需调整导入路径和执行语句:

from PyQt6.QtWidgets import QMainWindow, QApplication
from PyQt6.QtGui import QIcon
import sys

# 类结构同上,仅修改启动语句
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

Qt C++ 对应代码

#include <QMainWindow>
#include <QIcon>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowIcon(QIcon("your_icon_path.png"));
    // 其他界面初始化代码
}

方法二:自定义标题栏的图标添加

如果你的窗口隐藏了原生标题栏(比如设置Qt::FramelessWindowHint),需要手动在自定义标题栏的左上角添加图标控件:

代码示例(PyQt5)

from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QHBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 隐藏原生标题栏
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 创建自定义标题栏
        self.build_custom_title_bar()
        self.init_interface()

    def build_custom_title_bar(self):
        title_bar = QWidget()
        layout = QHBoxLayout(title_bar)
        layout.setContentsMargins(8, 8, 8, 8)

        # 添加图标标签
        icon_label = QLabel()
        # 缩放图标到合适尺寸,保持比例
        icon_pixmap = QPixmap("your_icon_path.png").scaled(32, 32, Qt.KeepAspectRatio)
        icon_label.setPixmap(icon_pixmap)
        layout.addWidget(icon_label)

        # 可继续添加标题文本、窗口控制按钮(最小化、关闭等)
        # ...

        # 将自定义标题栏设置为窗口的菜单部件
        self.setMenuWidget(title_bar)

    def init_interface(self):
        self.setGeometry(300, 300, 800, 600)
        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

注意事项

  • 图标推荐使用png、ico(Windows)、icns(Mac)格式,尺寸建议为32×32或64×64像素
  • 确保图标文件路径正确,可使用绝对路径或项目相对路径
  • 不同平台对窗口图标的显示规则略有差异,测试时尽量覆盖目标平台

内容的提问来源于stack exchange,提问作者asmbaty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:45:58