使用QFileDialog选择目录并将其导入python脚本

时间:2016-06-06 12:46:56

标签: python qt pyqt qfiledialog

我真的在这里亏本。我的设置如下:我使用QtDesigner创建一个GUI并获得ui.py。我有一个包装器,我对名为ui_module.py的信号进行了修改。然后是我导入ui_module.py的主程序。在这个主程序中,我希望目录的字符串能够在没有任何GUI的情况下进一步使用它(保存一些文件)。

这是一个MWE:

# ui.py
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(328, 269)

        # create a button and a label where the file path is displayed
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.savepathButton = QtGui.QPushButton(Form)
        self.savepathButton.setObjectName(_fromUtf8("savepathButton"))
        self.savepath_label = QtGui.QLabel(Form)
        self.savepath_label.setObjectName(_fromUtf8("savepath_label"))
        self.verticalLayout.addWidget(savepathButton)
        self.verticalLayout.addWidget(savepath_label)

这是包装器:

# ui_module.py
from PyQt4.QtGui import QApplication, QDialog, QAction, QFileDialog
from ui import Ui_Form


class AppWindow(QDialog):

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.show()

        # current directory as label text
        self.ui.savepath_label.setText("{}\data".format(os.getcwd().replace("\\\\", "\\")))


        # this is the part where I have to guess what I do
        # how do I update the label text after the button press?
        self.ui.savepathButton.pressed.connect(lambda: self.file_save())



    def file_save(self):
        path = QFileDialog.getExistingDirectory(self, "Choose directory")
        self.ui.savepath_label.setText(path)

if __name__ == "__main__":
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())

这是主程序:

import ui_module

app = ui_module.AppWindow()
    app.show()
    result = app.exec_()

    if result == 1:
        # how do I get the string of the filepath here?

我不确定在哪里我最好指定QFileDialog信号以及如何将实际字符串传送到我的主程序中。如果可能的话我想避免修改ui.py,因为那是我从QtDesigner获得的文件。

感谢您的帮助!

0 个答案:

没有答案