如何在Qt控制台应用程序中处理按键事件
How to handle keypress events in a Qt console application?
例如,当你按"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或其他库(诅咒)。
相关文章:
- 从文本文件中读取时钟时间和事件时间并进行处理
- 处理闪烁窗口事件
- 给定顺序中的事件处理
- C++事件系统 - 多态事件和事件处理程序
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 是否可以在QT GUI应用程序中处理事件时播放加载动画指示器?
- 如果窗口服务被杀,如何处理事件
- GRPC C 称为PloteimionQueue关闭,但PostemionQueue.Next在有待处理事件时永远阻
- WNDPROC处理事件更少的代码
- C FLTK 1.3.2:最新的屏幕,处理事件和非障碍睡眠
- 在运行线程中处理事件
- 如何在Windows C++中处理事件
- 使用 EVT_NAVIGATION_KEY 处理事件不起作用
- C++ 从另一个程序集创建 WPF 窗口的父级并处理事件
- 在QT OpenGL中处理事件
- 如何在QThread上处理事件
- 移动精灵和处理事件
- 如何处理事件消息,同时使用chrome嵌入式框架(CEF)
- 处理事件从wxTextCtrl在wxFrame - c++ /wxWidgets
- Qt如何处理事件发出的无限循环?