3

I would like to handle keyboard events in command line application based on QCoreApplication class. Following http://doc.qt.nokia.com/4.7/eventsandfilters.html I tried to reimplementing QCoreApplication::event(), but my code not works:

#include <QCoreApplication>
#include <QtGui/QKeyEvent>

class CoreApp : public QCoreApplication
{
Q_OBJECT
public:
    explicit CoreApp(int & argc, char ** argv);
    bool event(QEvent *event);
};

CoreApp::CoreApp(int & argc, char ** argv) :
    QCoreApplication(argc,argv)
{
}

bool CoreApp::event(QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_Q) {
            qDebug("Quit?");
            //qApp->quit();
            return true;
        }
    }
    return QCoreApplication::event(event);
}

int main(int argc, char *argv[])
{
    CoreApp a(argc, argv);
    return a.exec();
}

I've checked http://doc.qt.nokia.com/qq/qq11-events.html and didn't find solution. How to handle these events properly?

morfis
  • 133
  • 2
  • 8
  • Unfortunately Qt cannot get keyboard and mouse events from the console. http://stackoverflow.com/questions/7543313/how-to-handle-keypress-events-in-a-qt-console-application – Arnold Spence Nov 06 '11 at 03:22
  • @Arnold: Well, yes and no. You _can_ handle them. You need to open stdin as a socket and listen to it. http://stackoverflow.com/questions/1271784/using-qtextstream-to-read-stdin-in-a-non-blocking-fashion gives an example on how to do that. – Robin Nov 07 '11 at 14:40
  • @Robin I would like to every specified key pressed/character typed in terminal emits signal or triggers event. It seems to me that in your example only occurring of line in stdin emits signal. – morfis Nov 12 '11 at 17:03

0 Answers0