PySide2 在文件对话框中显示与主图标相同的图标 window

PySide2 display same icon in file dialog as main window

我有一个简单的 pyside2 应用程序,看起来有点像这样:

import sys
from PySide2.QtWidgets import QApplication, QDialog, QPushButton, QFileDialog, QVBoxLayout
from PySide2 import QtGui

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("My Form")
        self.setWindowIcon(QtGui.QIcon("myicon.png"))
        layout = QVBoxLayout()
        self.button = QPushButton("Open dialog")
        self.button.clicked.connect(self.browse)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def browse(self):
        qfd = QFileDialog()
        qfd.setWindowIcon(QtGui.QIcon("myicon.png"))
        filename, _ = qfd.getOpenFileName(None, "Load Data", ".", "*.txt")



if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())

我想为 QFileDialog 设置与主 window 图标相同的图标,但由于某些原因它不起作用。有没有办法像我在上面尝试的那样设置它?提前感谢您的想法、指点和帮助! (我正在使用 Ubuntu 20.04)

getOpenFileName 方法是一种静态方法,它创建除“qfd”之外的内部 QFileDialog,因此不应用图标。一种可能的选择是不使用 getOpenFileName,而是仅使用 QFileDialog class 创建逻辑,另一种解决方案是使用顶层特征访问在 getOpenFileName 中创建的 QFileDialog 对象:

import sys

from PySide2 import QtCore, QtGui, QtWidgets


class Form(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("My Form")
        self.setWindowIcon(QtGui.QIcon("myicon.png"))
        layout = QtWidgets.QVBoxLayout(self)
        self.button = QtWidgets.QPushButton("Open dialog")
        self.button.clicked.connect(self.browse)
        layout.addWidget(self.button)

    def browse(self):
        QtCore.QTimer.singleShot(0, self.handle_timeout)
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None,
            "Load Data",
            ".",
            "*.txt",
            options=QtWidgets.QFileDialog.DontUseNativeDialog,
        )

    def handle_timeout(self):
        for w in QtWidgets.QApplication.topLevelWidgets():
            if isinstance(w, QtWidgets.QFileDialog):
                w.setWindowIcon(QtGui.QIcon("myicon.png"))


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    form = Form()
    form.show()

    sys.exit(app.exec_())