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

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

相关推荐
Quz11 小时前
QML PathView:吸附对齐与环形轮播
qt
时间的拾荒人11 小时前
Qt 多线程详解:从 QThread 到实战
开发语言·qt·面试
时间的拾荒人14 小时前
Qt 事件机制全解析:从事件处理到事件过滤器
开发语言·qt·面试
时间的拾荒人17 小时前
Qt 窗口系统详解:从菜单栏到对话框的完整指南
开发语言·qt·面试
qq_4017004118 小时前
Qt 炫酷曲线,图表,2D/3D开源库
开发语言·qt
扶尔魔ocy19 小时前
【qt openGL入门笔记】基础光照
qt·opengl
时间的拾荒人20 小时前
Qt 文件操作详解:从基础类到读写实战
开发语言·qt·面试
扶尔魔ocy1 天前
【qt openGL入门笔记】坐标系统和摄像机
qt·opengl
C++ 老炮儿的技术栈2 天前
main函数之后的调用
c语言·c++·人工智能·qt·mfc·c
沫璃染墨2 天前
《Qt从零入门系列(十二):Qt文件操作详解——从QFile读写到QFileInfo与记事本实战》
开发语言·网络·c++·qt·交互·信号处理·文件