我正在尝试使用python3在pyqt5中创建路径浏览器,但我有些疑惑。我的代码是这样的:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(300, 150, 160, 80))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout.addWidget(self.lineEdit)
self.toolButton = QtWidgets.QToolButton(self.horizontalLayoutWidget)
self.toolButton.setObjectName("toolButton")
self.horizontalLayout.addWidget(self.toolButton)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
# Button action
self.toolButton.pressed.connect(self.selectDirectory(MainWindow, self.lineEdit))
def selectDirectory(self, MainWindow, editText):
editText.setText(str(QtWidgets.QFileDialog.getExistingDirectory(MainWindow, "Select Directory", str(editText.text()))))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Path"))
self.toolButton.setText(_translate("MainWindow", "..."))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
这个想法是使用edittext来编写文件夹的路径,但作为帮助器,我想引入一个按钮来打开文件浏览器以选择目录。为了实现这一点,我试图使用QFileDialog但没有成功。我现在的问题是当我运行我的应用程序时,显示QFileDialog,当我选择文件夹时应用程序崩溃。第一件事我不想在没有按下按钮的情况下显示QFileDialog,第二件事我不明白为什么应用程序崩溃了这个错误:
Traceback (most recent call last):
File "test.py", line 48, in <module>
ui.setupUi(MainWindow)
File "test.py", line 31, in setupUi
self.toolButton.pressed.connect(self.selectDirectory(MainWindow, self.lineEdit))
TypeError: argument 1 has unexpected type 'NoneType'
感谢您的帮助
答案 0 :(得分:0)
信号pressed
希望连接到不期望参数的插槽,因此不能与selectDirectory()
函数直接连接,必须使用lambda函数建立连接。 / p>
你必须改变
self.toolButton.pressed.connect(self.selectDirectory(MainWindow, self.lineEdit))
到
self.toolButton.pressed.connect(lambda m=MainWindow, l=self.lineEdit: self.selectDirectory(m, l))