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

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

相关推荐
Tianwen_Burning20 小时前
点云在qt的QVTKOpenGLNativeWidget控件上显示
qt·halcon3d
南桥几晴秋21 小时前
QT按钮控件
开发语言·qt
MindCareers1 天前
Beta Sprint Day 1-2: Alpha Issue Fixes Initiated + Mobile Project Setup
android·c语言·数据库·c++·qt·sprint·issue
环黄金线HHJX.1 天前
【MCP: Tuan编程 + Qt架构 + QoS - 量子-经典混合计算管理控制平台】
ide·人工智能·qt·编辑器·量子计算
雒珣1 天前
qt界面和图片疯狂变大的bug问题
开发语言·qt·bug
leiming61 天前
c++qt开发第三天 摄像头采集视频
开发语言·c++·qt
QQ_4376643141 天前
Qt-框架
c++·qt
※※冰馨※※1 天前
【QT】初始化显示时正常,操作刷新后布局显示问题。
开发语言·c++·windows·qt
溟洵1 天前
【C++ Qt 】中的多线程QThread已经线程安全相关的锁QMutex、QMutexLocker
c++·后端·qt
Lhan.zzZ1 天前
嵌入式Qt接收串口数据错乱问题分析:缓冲区残留数据的陷阱
开发语言·c++·qt