PyQt:QtGui.QFileDialog.getSaveFileName在选择后不会关闭

时间:2013-02-26 17:11:36

标签: python pyqt pyqt4 qfiledialog

在我的PyQt4应用程序中,有一项功能允许用户保存 avi 文件。 为此,在主窗口中实现了 saveMovie 方法:

def saveMovie(self):
    """ Let the user make a movie out of the current experiment. """
    filename = QtGui.QFileDialog.getSaveFileName(self, "Export Movie", "",
                                                 'AVI Movie File (*.avi)')

    if filename != "":
        dialog = QtGui.QProgressDialog('',
                                       QtCore.QString(),
                                       0, 100,
                                       self,
                                       QtCore.Qt.Dialog |
                                       QtCore.Qt.WindowTitleHint)

        dialog.setWindowModality(QtCore.Qt.WindowModal)
        dialog.setWindowTitle('Exporting Movie')
        dialog.setLabelText('Resampling...')

        dialog.show()

        make_movie(self.appStatus, filename, dialog)

        dialog.close()

我的想法是使用 QProgressDialog 来显示视频编码工作的进展情况。
然而,在选择文件名后, QFileDialog 不会消失,整个应用程序将保持无响应,直到 make_movie 功能完成。

我该怎么做才能避免这种情况?

1 个答案:

答案 0 :(得分:2)

经验教训:如果你有一些长时间运行的操作 - 例如,读取或写入文件,将它们移动到另一个线程,否则它们将冻结UI。

因此,我创建了一个QThreadMovieMaker的子类,其run方法封装了make_movie通常实现的功能:

class MovieMaker(QThread):
    def __init__(self, uAppStatus, uFilename):
        QtCore.QThread.__init__(self, parent=None)
        self.appStatus = uAppStatus
        self.filename = uFilename

    def run(self):
        ## make the movie and save it on file

让我们回到saveMovie方法。在这里,我使用以下代码将原始调用替换为make_movie

self.mm = MovieMaker(self.appStatus,
                     filename)

self.connect(self.mm, QtCore.SIGNAL("Progress(int)"),
             self.updateProgressDialog)

self.mm.start()

请注意我如何定义新的信号Progress(int) MovieMaker线程发出此类信号,以更新 QProgressDialog ,用于向用户显示电影编码工作的进展情况。

相关问题