如何使按钮执行单击而不是双击

时间:2017-03-10 10:19:12

标签: python-3.x user-interface pyqt mouseevent pyqt5

我正在试验PyQt5。当我输入一个值并单击按钮传递在我的行编辑中输入的值时,我注意到它需要点击2次鼠标才能通过,并在我的纯文本编辑中显示该值。

我如何更改我的代码,以便只需点击一下就可以传输行编辑中输入的值?

from PyQt5 import QtCore, QtGui, QtWidgets
from functools import partial

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(640, 480)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(40, 80, 151, 31))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(190, 90, 113, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(40, 170, 181, 16))
        self.label_2.setObjectName("label_2")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(Form)
        self.plainTextEdit.setGeometry(QtCore.QRect(220, 170, 104, 71))
        self.plainTextEdit.setReadOnly(True)
        self.plainTextEdit.setObjectName("plainTextEdit")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(310, 90, 75, 23))
        self.pushButton.setObjectName("pushButton")


        self.pushButton.clicked.connect(self.Pass)


        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "Pass the value entered here:"))
        self.label_2.setText(_translate("Form", "Accept and display the passed value:"))
        self.pushButton.setText(_translate("Form", "PASS"))



    def Pass(self):

        accept = self.lineEdit.text()

        self.pushButton.clicked.connect(partial(self.Get, accept))

    def Get(self, getA):

        self.plainTextEdit.setPlainText(getA)




if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()

    ui.Get(ui.Pass())

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:3)

.clicked 在您第一次点击按钮时触发。但问题是您将Pass注册到按钮:

self.pushButton.clicked.connect(self.Pass)

现在Pass定义为:

def Pass(self):
    accept = self.lineEdit.text()
    # connect a new event
    self.pushButton.clicked.connect(partial(self.Get, accept))

因此,当您第一次点击该按钮时,您只能阅读按钮的accept connect self.Get方法,以便下次按下按钮时,确实会调用self.Get

为了立即处理请求,您只需将Pass方法修改为:

即可
def Pass(self):
    accept = self.lineEdit.text()
    self.Get(accept)