通过线程控制QT控制台程序退出

QT控制台程序运行后通过一个单独线程监视用户输入退出程序(用户输入Q并按回车后退出控制台程序)。


监控线程头文件:

#include <QThread>

class CMyKeyEventThread : public QThread
{
    Q_OBJECT
public:
    explicit CMyKeyEventThread(QObject *parent = 0);

protected:
    void run();
};

监控线程源文件:

#include "cmykeyevent.h"
#include <stdio.h>

CMyKeyEventThread::CMyKeyEventThread(QObject *parent) : QThread(parent)
{

}

void CMyKeyEventThread::run()
{
    char *pszTip = "Press 'Q' exit application.\n";
    while (true)
    {
        printf("%s", pszTip);
        if (getchar() == 'Q')
        {
            break;
        }
    }

    printf("Done.");
}


main.cpp文件:

#include <QCoreApplication>
#include "cmykeyevent.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    CMyKeyEventThread *exitEvent = new CMyKeyEventThread();
    QObject::connect(exitEvent, SIGNAL(finished()), &a, SLOT(quit()));//连接信号
    exitEvent->start();//启动线程

    return a.exec();
}





你可能感兴趣的:(通过线程控制QT控制台程序退出)