Daniel Severo
Daniel Severo

Reputation: 1848

QLineEdit not updating text with QKeyEvent

I'm trying to implement a virtual keyboard widget. The simplest way I could think of is to create QKeyEvent instances and send them with QApplication.postEvent() to the widget in focus.

First, I'm trying to update a fixed QLineEdit that I have, so the code is:

   self.pushButton_A.clicked.connect(self.virtualKeyPress)

[...]

   def virtualKeyPress(self):
        self.keyPress = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.NoModifier)
        QApplication.postEvent(self.lineEdit, self.keyPress)

But the QLineEdit instance won't update its text in the GUI!

Clues? Cheers and thanks!

RESOLVED: (kudos to HeyYO)

   self.pushButton_A.clicked.connect(self.virtualKeyPress)

[...]

   def virtualKeyPress(self):
        self.keyPress = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.NoModifier, 'A')
        QApplication.postEvent(self.lineEdit, self.keyPress)

In my case, inplace of Qt.Key_A I set that argument to 0 so that I can connect all my buttons to the virtualKeyPress method. I also had to set the focus policy for all the buttons to 'no focus' (did it directly in Qt Designer). The final code was the following:

def virtualKeyPress(self):
    self.keyPressed = QString(self.sender().text())
    self.keyPress = QKeyEvent(QEvent.KeyPress, 0, Qt.NoModifier, self.keyPressed)
    self.focusWidget = QApplication.focusWidget()        
    QApplication.postEvent(self.focusWidget, self.keyPress)

Upvotes: 2

Views: 696

Answers (1)

HeyYO
HeyYO

Reputation: 2073

Have you tried specifying the text argument;

self.keyPress = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.NoModifier, "A")

It worked for me, in Qt5&C++, so I'm assuming it will work for you as well.

Upvotes: 4

Related Questions