Adding QFileDialog as a widget inside another QDialog

淺唱寂寞╮ 提交于 2019-12-02 17:57:55

问题


I'm attempting to create a dialog which contains two child widgets: on the left side a QFileDialog instance so users can select files, and on the right side a separate widget which will be used to show a preview of the selected file if it is of a certain type.

The problem is that the dialog opens up and I can see the "preview" widget just fine, but the QFileDialog is not showing up at all.

This short example demonstrates my problem:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

app = QApplication([])

main_dialog = QDialog()
main_dialog.setWindowTitle('My Dialog')
layout = QHBoxLayout(main_dialog)

file_dialog = QFileDialog(main_dialog, Qt.Widget)
file_dialog.setOption(QFileDialog.DontUseNativeDialog)
layout.addWidget(file_dialog)

preview = QLabel('Preview', main_dialog)
layout.addWidget(preview)

main_dialog.show()

app.exec_()

Some things that I've tried:

  1. Add file_dialog.show() before/after main_dialog.show(): this shows up the QFileDialog, but in a different window; I want the file dialog to appear inside main_dialog, not as a separate window;
  2. Do not pass Qt.Widget to the QFileDialog constructor, to no effect;
  3. Do not pass main_dialog as parent to QFileDialog, again no effect;
  4. Change main_dialog to a QWidget just to see if it changed anything, it did not;

I've searched the docs but did not find a suitable solution.

Any hints? Also, suggestions on how to accomplish the task of allowing the user to select a file and display a preview of the file in the same window are welcome.

Context: this is a port of an old application written for Qt3. Qt3's QFileSystem dialog had this "preview" functionality built-in; I'm trying to reproduce the same functionality in Qt5.

Versions

  • Python 2.7
  • PyQt 5.5.1

I've also tried with Python 3.6 (from conda-forge) but obtained the same behavior.


回答1:


You need to turn off the Qt.Dialog flag in the file dialog's windowFlags...

file_dialog.setWindowFlags(file_dialog.windowFlags() & ~Qt.Dialog)

Otherwise the QFileDialog will always be created as a top level window. Works for me anyway.



来源:https://stackoverflow.com/questions/45986165/adding-qfiledialog-as-a-widget-inside-another-qdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!