QFileDialog总是在主窗口后打开

问题描述 投票:1回答:1

我正在尝试在PySide2应用程序中打开文件,但是文件对话框始终在主窗口下方打开,并在启动器中显示为另一个应用程序。该应用程序的名称为“门户”。

我看到other answers的解决方案是将主窗口作为第一个参数传递给getOpenFileName(),但这对我不起作用。

这是问题的简单说明:

import sys
from PySide2.QtWidgets import QPushButton, QFileDialog, QApplication


class DemoButton(QPushButton):
    def __init__(self, text):
        super().__init__(text)
        self.clicked.connect(self.on_click)

    def on_click(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "Open a text file.",
            filter='Text file (*.txt)')
        print(file_name)


def main():
    app = QApplication(sys.argv)
    button = DemoButton("Hello World")
    button.show()
    app.exec_()
    sys.exit()


main()

我以为父母可能必须是QMainWindow,所以我尝试了:

import sys

from PySide2 import QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        main_widget = QtWidgets.QWidget(self)
        self.setCentralWidget(main_widget)

        # layout initialize
        g_layout = QtWidgets.QVBoxLayout()
        layout = QtWidgets.QFormLayout()
        main_widget.setLayout(g_layout)

        # Add Widgets
        self.exec_btn = QtWidgets.QPushButton('Execute')
        self.exec_btn.clicked.connect(self.find_file)

        # global layout setting
        g_layout.addLayout(layout)
        g_layout.addWidget(self.exec_btn)

    def find_file(self):
        file_name, _ = QtWidgets.QFileDialog.getOpenFileName(
            self,
            "Open a text file.",
            filter='Text file (*.txt)')
        print(file_name)


def main():
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()
    sys.exit()


main()

文件对话框的行为完全相同。

我正在使用PySide2 5.12.2,Python 3.6.7,并在Ubuntu 18.04上运行。

python pyside2
1个回答
0
投票

由于ekhumoro的评论,我了解到我可以告诉PySide2不要使用本机文件对话框。

import sys
from PySide2.QtWidgets import QPushButton, QFileDialog, QApplication


class DemoButton(QPushButton):
    def __init__(self, text):
        super().__init__(text)
        self.clicked.connect(self.on_click)

    def on_click(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "Open a text file.",
            filter='Text file (*.txt)',
            options=QFileDialog.DontUseNativeDialog)
        print(file_name)


def main():
    app = QApplication(sys.argv)
    button = DemoButton("Hello World")
    button.show()
    app.exec_()
    sys.exit()


main()

这通过将文件对话框置于最前面来解决此问题,但是我认为本机文件对话框看起来更好。希望有另一个选项可以使本机文件对话框正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.