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函数即可。

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

相关推荐
NiNi_suanfa3 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
mengzhi啊4 小时前
c++11的变参模板和c++17的左折叠
qt
路痴楷6 小时前
无法定位程序输入点问题
c++·qt·visual studio
Source.Liu6 小时前
【LibreCAD】 RS_Units 类完整解析
c++·qt·rust
偶像你挑的噻7 小时前
2.Qt-基础核心以及信号与槽
开发语言·qt
爱吃巧克力的程序媛12 小时前
Qt 异步编程---概述
开发语言·qt
天涯路s13 小时前
qt怎么自定义日志
开发语言·qt
四维碎片15 小时前
【Qt】QTimer 学习笔记总结
笔记·qt·学习
qq_4017004116 小时前
理解与优化Qt信号槽机制提高性能优化
qt
蚂蚁取经17 小时前
Qt C++ 小部件 QCustomPlot 的使用
c++·qt·信息可视化