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

2024-09-30 16:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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设置与主窗口图标相同的图标,但由于某些原因,它不起作用。有没有办法把它设置成我在上面尝试的样子?提前感谢您的想法、建议和帮助!(我正在使用Ubuntu 20.04)


Tags: thefromimportselfformsysbuttonlayout
1条回答
网友
1楼 · 发布于 2024-09-30 16:38:13

getOpenFileName方法是一种静态方法,它创建除“qfd”之外的内部QFileDialog,因此不应用图标。一种可能的选择是不使用getOpenFileName,而是仅使用QFileDialog类创建逻辑,另一种解决方案是使用顶级特性访问在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_())

相关问题 更多 >