如何在Qt控制台应用程序中处理按键事件

How to handle keypress events in a Qt console application?

本文关键字:处理 事件 应用程序 Qt 控制台      更新时间:2023-10-16

例如,当你按"Esc"键时,应用程序结束

这是linux的一个解决方案。使用这些帖子

从标准输入中捕获字符,而不必等待按enter键https://stackoverflow.com/a/912796/2699984

我是这样写的:

ConsoleReader.h

#ifndef CONSOLEREADER_H
#define CONSOLEREADER_H
#include <QThread>
class ConsoleReader : public QThread
{
    Q_OBJECT
signals:
    void KeyPressed(char ch);
public:
   ConsoleReader();
   ~ConsoleReader();
   void run();
};
#endif  /* CONSOLEREADER_H */

ConsoleReader.cpp

#include "ConsoleReader.h"
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
static struct termios oldSettings;
static struct termios newSettings;
/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &oldSettings); /* grab old terminal i/o settings */
  newSettings = oldSettings; /* make new settings same as old settings */
  newSettings.c_lflag &= ~ICANON; /* disable buffered i/o */
  newSettings.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &newSettings); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &oldSettings);
}
/* Read 1 character without echo */
char getch(void) 
{
  return getchar();
}
ConsoleReader::ConsoleReader()
{
  initTermios(0);
}
ConsoleReader::~ConsoleReader()
{
  resetTermios();
}
void ConsoleReader::run()
{
    forever
    {
        char key = getch();        
        emit KeyPressed(key);
    }
}

然后启动新线程读取键:

ConsoleReader *consoleReader = new ConsoleReader();
connect (consoleReader, SIGNAL (KeyPressed(char)), this, SLOT(OnConsoleKeyPressed(char)));
consoleReader->start();

*更新(增加了在退出时恢复终端设置)

如果您只需要'quit',那么下面的代码段可能会有所帮助(需要c++11和qt5):

#include <iostream>
#include <future>
#include <QCoreApplication>
#include <QTimer>
int main(int argc, char *argv[])
{
    QCoreApplication application(argc, argv);
    bool exitFlag = false;
    auto f = std::async(std::launch::async, [&exitFlag]{
        std::getchar();
        exitFlag = true;
    });
    QTimer exitTimer;
    exitTimer.setInterval(500);
    exitTimer.setSingleShot(false);
    QObject::connect(&exitTimer,
                     &QTimer::timeout,
                     [&application,&exitFlag] {
        if (exitFlag)
            application.quit();
    });
    exitTimer.start();
    std::cout << "Started! Press Enter to quit...";
    int ret =  application.exec();
    std::cout.flush();
    f.wait();
    return ret;
}

Qt不处理控制台事件,它只能从控制台读取n终止的行。

您需要使用本机api或其他库(诅咒)。