简体   繁体   English

Pyqt4:通过文件浏览小部件编辑QLineEdit文本并将其作为参数发送

[英]Pyqt4: Editing QLineEdit text via file browsing widget and sending it as a parameter

I'm trying to create an app which should allow to choose a directory and after pressing the button send the selected path to another function outside the App class. 我正在尝试创建一个应允许选择目录的应用,并在按下按钮后将所选路径发送到App类之外的另一个函数。 Also there is a predefined directory set as default path and displayed in the QLineEdit widget. 此外,还有一个预定义目录设置为默认路径,并显示在QLineEdit小部件中。 This is what I've tried: 这是我尝试过的:

import os
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from functools import partial

class App (QtGui.QMainWindow):

    def __init__(self):
        super(App, self).__init__()
        self.initUI()

    def initUI(self):

        default_path = os.path.dirname(os.path.abspath(__file__))

        def selectDir():
            labelSavePath.setText(QtGui.QFileDialog.getExistingDirectory(self,
                                                         'Select Dir:'))

        self.setFixedSize(450, 150)
        self.setWindowTitle('App')

        labelSavePath = QtGui.QLineEdit(default_path, self)
        labelSavePath.setGeometry(15, 72, 340, 20)
        labelSavePath.setAlignment(QtCore.Qt.AlignLeft)
        labelSavePath.setReadOnly(True)

        btnBrowse = QtGui.QPushButton('Browse', self)
        btnBrowse.setGeometry(365, 67, 80, 30)

        btnBrowse.clicked.connect(selectDir)

        btnStart = QtGui.QPushButton('Start', self)
        btnStart.move(345, 115)
        btnStart.clicked.connect(partial(startRun,
                                 str(labelSavePath.text())))

        self.show()

def startRun(log_path):
    print(log_path) #and do smth useful

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    w = App()
    sys.exit(app.exec_())

However, the log_path is always equal to default_path no matter if it is changed by the user or not. 但是,无论用户是否更改了log_path,它始终等于default_path I have been looking for the answer for a couple of hours already and still haven't managed to find the bug, since I'm new to PyQt. 由于我是PyQt的新手,所以我已经在寻找答案的几个小时了,但仍然没有找到该错误。

How should I edit/pass the text in the labelSavedPath widget correctly, minding possible changes? 考虑可能的更改,如何正确编辑/传递labelSavedPath小部件中的文本?

You seem to have misunderstood what partial does. 您似乎误解了部分功能。 It allows you to call a function with some its arguments pre-filled with fixed values - which is exactly what you don't want. 它允许您调用带有某些参数的函数,这些参数的参数预先填充有固定值-这正是您所不想要的。 Use a lambda instead: 改用lambda

    btnStart.clicked.connect(lambda: startRun(labelSavePath.text()))

NB: if you're using Python 3, there's no need to wrap everything with str() . 注意:如果您使用的是Python 3,则无需使用str()包装所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM