Qt Whenever pressed enter in QTextEdit

Normal People Scare Me picture Normal People Scare Me · May 2, 2013 · Viewed 7.1k times · Source

Whenever I pressed enter in my QTextEdit it'll perform a click on my login button. Somehow this causes a crash of my QtCreator. How can I change what'll happen If I press enter in my QTextEdit?

Answer

Luc Touraille picture Luc Touraille · May 2, 2013

You need to subclass QTextEdit and catch the event you're interested in by overriding the appropriate method:

class MyTextEdit : public QTextEdit
{
    Q_OBJECT
public:
    void MyTextEdit::keyPressEvent(QKeyEvent *event)
    {
        if (event->key() == Qt::Key_Return)
        {
            login(); // or rather emit submitted() or something along this way
        }
        else
        {
            QTextEdit::keyPressEvent(event);
        }
    }
};

Alternatively, you can install an event filter on the text edit.