QT下,如何获取控制台输入

最近工作中为了测试某个模块,需要把原先输入模块部分,改成控制台输入来方便测试。在QT中,我们可以使用 QTextStream 类来读取用户的输入来达到目的。下面是一个简单的例子:

cpp 复制代码
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
    
    QTextStream cin(stdin);
    QString input;
    while (true) {
        input = cin.readLine();
        if (input == "q") {
            break;
        }
        qDebug() << "You entered: " << input;
    }

    return app.exec();
}

当然,我们也可以把这段代码写到一个线程中来执行,例如:

cpp 复制代码
void startForTestThread()
{
    QThread threadM;
    ForTest pForTestM = new ForTest();
    pForTestM->moveToThread(&threadM);
    threadM.start();
    connect(&threadM, SIGNAL(started()), this, SLOT(waitForEnter()));
}

void waitForEnter()
{
    // for test
    QTextStream cin(stdin);

    QString input;
    while (true) {
        input = cin.readLine();
        if (input == "q") {
            break;
        }
        qDebug() << "You entered: " << input;
        
        // do something with "input"
        sendSignalSimulate(input.toInt());
    }
}

只要在你的程序合适位置调用startForTestThread函数即可。

综上,我们就可以通过输入不同的参数来进行测试了。

相关推荐
2401_8534482312 小时前
tslib及QT移植
qt·tslib
IOT-Power13 小时前
Qt 输入框: 数字/浮点/十六进制数值输入处理
qt
神仙别闹17 小时前
基于QT(C++)实现宠物小精灵对战游戏
c++·qt·宠物
小尧嵌入式18 小时前
音视频入门基础知识
开发语言·c++·qt·算法·音视频
蓑衣夜行18 小时前
QtWebEngine 自动重启方案
开发语言·c++·qt·web·qwebengine
Source.Liu18 小时前
【LibreCAD】点实体源码解析
c++·qt·cad
乌托邦2号18 小时前
Qt5之中文字符串转换
开发语言·qt
IOT-Power19 小时前
QT QSerialPort 串口不稳定,串口是否使用独立线程
qt
IOT-Power20 小时前
QT的解耦方式
qt
定义小花21 小时前
c++ cmake qt
开发语言·c++·qt