0

我有以下简单的 Qt 应用程序,它根据给定的文本创建系统托盘图标。当我通过 vscode 终端运行应用程序时,一切似乎都很好(见下面的截图):

在此处输入图像描述

奇怪的是,当我通过系统终端 (bash) 运行应用程序时,图标大小不受尊重,并且文本被缩小(见下文):

在此处输入图像描述

如果有人能阐明可能导致这种奇怪行为的原因,我将不胜感激。这是代码:

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtWidgets, QtGui, QtSvg


def create_tray_icon(label):
    r"""Creates QIcon with the given label."""
    w, h = 22*4, 22
    pixmap = QtGui.QPixmap(w, h)
    pixmap.fill(QtCore.Qt.transparent)  # alternative: QtGui.QColor("white")
    painter = QtGui.QPainter(pixmap)
    painter.setPen(QtGui.QColor("white"))
    align = int(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
    painter.drawText(pixmap.rect(), align, str(label))
    painter.end()
    icon = QtGui.QIcon()
    icon.addPixmap(pixmap)
    return icon


class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
        self.menu = QtWidgets.QMenu(parent)
        exitAction = self.menu.addAction("Exit")
        exitAction.triggered.connect(lambda: sys.exit())
        self.setContextMenu(self.menu)


def memprofilerApp():
    r"""Runs the Qt Application."""
    QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    app = QApplication(sys.argv)
    icon = create_tray_icon(label="Hello world!")
    trayIcon = SystemTrayIcon(icon)
    trayIcon.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    memprofilerApp()
4

1 回答 1

0

在 vscode 终端上检查环境变量(通过运行env)并将其与系统终端上的环境变量进行比较后,结果发现罪魁祸首是XDG_CURRENT_DESKTOP!在 vscode 终端(遵循 QIcon 大小)中,它设置为UNITY,而在系统终端中,它设置为ubuntu:GNOME

我不知道根本原因,但快速解决方法是使用以下脚本运行应用程序:

#!/bin/bash
XDG_CURRENT_DESKTOP=Unity
/path/to/python main.py

只是出于好奇,如果有人知道为什么ubuntu:GNOME会导致 QIcon 尺寸损坏,请告诉我们!

于 2021-10-06T23:39:17.477 回答