I'm trying to open a file in my PySide2 application, but the file dialog always opens below the main window and appears as another application in the launcher. The application's name is "Portal".
I see other answers where the solution is to pass the main window as the first parameter to getOpenFileName()
, but that doesn't work for me.
Here's a simple demonstration of the problem:
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()
I thought maybe the parent had to be a QMainWindow
, so I tried that:
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()
The file dialog behaved exactly the same.
I'm using PySide2 5.12.2, Python 3.6.7, and running on Ubuntu 18.04.
from QFileDialog always opens behind main window
No comments:
Post a Comment