2017-03-10 83 views
2

我正在試驗PyQt5。當我輸入一個值並單擊按鈕傳遞在我的行編輯中輸入的值時,我注意到它需要2次鼠標單擊才能通過,並在我的純文本編輯中顯示該值。如何使按鈕執行單擊而不是雙擊

我將如何改變我的代碼,使上線編輯輸入值由僅有1點擊通過?

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

否的原因是,你只添加了'GET'方法,第二次...... –

+0

你可以請進一步解釋? – harthart

回答

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,並只有connectself.Get方法的按鈕使得下一次你按下按鈕self.Get確實會被調用。

爲了處理請求直線距離,你可以簡單地修改Pass方法:

def Pass(self): 
    accept = self.lineEdit.text() 
    self.Get(accept)
+1

謝謝!這清除了很多混亂。我從來不知道這很簡單。榮譽給你! – harthart