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

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

相关推荐
森G35 分钟前
35、事件传递模式---------事件系统
c++·qt
怎么没有名字注册了啊2 小时前
崩溃解决_Qt子窗口关闭按钮后打开崩溃
开发语言·qt
笑鸿的学习笔记3 小时前
Qt与CMake笔记之option、宏传递与Qt Creator项目设置
开发语言·笔记·qt
森G5 小时前
40、对话框---------事件系统
c++·qt
Frank_refuel6 小时前
QT->信号与槽详解下补充(概述、使用、自定义、连接方式、其他说明)
开发语言·qt
小灰灰搞电子6 小时前
Qt UI 线程详解-阻塞与解决方案
开发语言·qt·ui
森G6 小时前
41、数据库---------事件系统
c++·qt
pl4H522a66 小时前
简易的分布式kv设计
windows·qt·microsoft
羽翼未丰的啊博1 天前
DBC_2_C上位机
qt·车载系统·汽车
大米粥哥哥1 天前
Qt 报错qt.qpa.plugin: Could not find the Qt platform plugin “xcb“ in ““【已解决】
开发语言·qt·plugin·linuxdeployqt·xcb