使用keypress在QLineEdit中输入文本并在PyQt4中发出信号

时间:2014-01-22 18:52:50

标签: python pyqt pyqt4 qlineedit

使用PyQt 4.8和Python 3.3

我正在使用this example的修改版本:虽然此示例在按Tab键上发出信号并将任意文本添加到第二个QLineEdit,但我希望我的脚本在任何按键上发出信号,添加将任意信号文本添加到第二个QLineEdit,并将键入的字符添加到第一个QLineEdit(假设它是一个有效的ASCII字符)。

每当我尝试使用任何按键作为信号时,我都无法再抓取该文本输入QLineEdit。这就是我到目前为止所遇到的以及我遇到的问题:

import sys
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

#################################################################### 
def main(): 
    app = QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_()) 

####################################################################
class MyWindow(QWidget): 
    def __init__(self, *args): 
        QWidget.__init__(self, *args)

        # create objects
        self.la = QLabel("Type in this box:")
        self.le = MyLineEdit()
        self.la2 = QLabel("\nLook here:")
        self.le2 = QLineEdit()
        self.char = MyLineEdit.char # HOW CAN I GET THIS WORKING?

        # layout
        layout = QVBoxLayout()
        layout.addWidget(self.la)
        layout.addWidget(self.le)
        layout.addWidget(self.la2)
        layout.addWidget(self.le2)
        self.setLayout(layout)

        # connections
        self.connect(self.le, SIGNAL("keyPressed"),
                     self.update)

    def update(self):
        newtext1 = self.le.text() + self.char
        newtext2 = self.le2.text() + "kP "
        self.le.setText(newtext1)
        self.le2.setText(newtext2)

####################################################################

class MyLineEdit(QLineEdit):
    def __init__(self, *args):
        QLineEdit.__init__(self, *args)

    def event(self, event):
        if (event.type() == QEvent.KeyPress):
            self.emit(SIGNAL("keyPressed"))
            self.char = "%c" % (event.key())
            return True

        return QLineEdit.event(self, event)

####################################################################
if __name__ == "__main__": 
    main()

非常感谢任何和所有帮助。 PyQt4中有什么东西允许我使用按键作为信号和输入文本,还是我的Python关闭?

1 个答案:

答案 0 :(得分:2)

问题1:在设置self.char

之前,您正在发出信号
class MyLineEdit(QLineEdit):
    def __init__(self, *args):
        QLineEdit.__init__(self, *args)
        self.char = ""

    def event(self, event):
        if (event.type() == QEvent.KeyPress):
            self.char = "%c" % (event.key()) #this line above the next
            self.emit(SIGNAL("keyPressed"))
            return True

        return QLineEdit.event(self, event)

问题2:使用MyLineEdit对象中的char值:

    def update(self):
        newtext1 = self.le.text() + self.le.char
        newtext2 = self.le2.text() + "kP "
        self.le.setText(newtext1)
        self.le2.setText(newtext2)

最后,self.char

上不需要MyWindow