在当前状态下调用代码时,会显示一个带有两个按钮和两个 QLineEdits 的窗口。
假设如果该行上没有注释#self.dataBrowse.clicked.connect(self.btnDataClicked())
,则按下顶部按钮打开QFileDialog
,该按钮将传输到相应的QLineEdit
文件名,并从那里获取名称以实现不在此处的代码。
当代码取消注释#self.dataBrowse.clicked.connect(self.btnDataClicked())
并运行时,会立即执行相应的函数。为什么会这样?
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QIcon
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent=None)
self.dataEdit = QtWidgets.QLineEdit()
self.sensorEdit = QtWidgets.QLineEdit()
self.dataBrowse = QtWidgets.QPushButton('Browse', self)
#self.dataBrowse.clicked.connect(self.btnDataClicked())
self.sensorBrowse = QtWidgets.QPushButton('Browse', self)
self.hbox_main = QtWidgets.QHBoxLayout()
self.vbox_left = QtWidgets.QVBoxLayout()
self.vbox_left.addWidget(self.dataEdit)
self.vbox_left.addWidget(self.sensorEdit)
self.vbox_right = QtWidgets.QVBoxLayout()
self.vbox_right.addWidget(self.dataBrowse)
self.vbox_right.addWidget(self.sensorBrowse)
self.hbox_main.addLayout(self.vbox_left)
self.hbox_main.addLayout(self.vbox_right)
self.setLayout(self.hbox_main)
def btnDataClicked(self):
fname = QtWidgets.QFileDialog.getOpenFileName(self)[0]
self.dataEdit.setText(fname)
def btnSensorClicked(self):
fname = QtWidgets.QFileDialog.getOpenFileName(self)[0]
self.sensorEdit.setText(fname)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.setWindowTitle("OOP")
window.show()
sys.exit(app.exec_())
PS我阅读了文档,但我仍然不明白,是否有可能传递btnClicked
必要的函数QLineEdit
,以免创建函数btnDataClicked
并对btnSensorClicked
不同的函数执行相同的操作QLineEdit
?
替换
self.dataBrowse.clicked.connect(self.btnDataClicked())
为self.dataBrowse.clicked.connect(self.btnDataClicked)