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

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

相关推荐
QtHalcon1 天前
YOLOv11 +QT环境安装+标注训练+部署
深度学习·qt·yolo
追烽少年x1 天前
Qt中QUdpSocket类的简单使用
qt
Y1rong1 天前
QT之自定义控件
qt
CC.GG1 天前
【Qt】常用控件----按钮类控件
开发语言·数据库·qt
郝学胜-神的一滴1 天前
Qt实现窗口阴影之美:光影交错间的界面艺术
开发语言·c++·qt·软件工程
小陈phd1 天前
大语言模型实战(十)——基于通义千问 + FastMCP 打造天气查询机器人
qt·语言模型·机器人
Larry_Yanan1 天前
Qt多进程(七)内存映射
开发语言·qt
_OP_CHEN1 天前
【从零开始的Qt开发指南】(十五)Qt窗口之对话框终极指南:从分类到实战,解锁交互设计新高度
开发语言·qt·前端开发·对话框·客户端开发·gui开发·qt窗口
带土12 天前
9. Qt Lambda
开发语言·qt
Morwit2 天前
如何使用CMake构建Qt新项目
开发语言·c++·qt