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

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

相关推荐
小短腿的代码世界2 小时前
QCefView深度解析:Qt应用中嵌入Chromium浏览器的终极方案
开发语言·qt
小短腿的代码世界6 小时前
VLC-Qt深度解析:Qt应用中的专业视频播放方案
开发语言·qt
rrr26 小时前
【前端开发】|GUI 基本概念和框架基础
前端·qt
Z文的博客7 小时前
【避坑实录】Qt 4.8.6 + Paho MQTT C客户端 + OpenSSL静态链接的血泪史
c语言·开发语言·qt·嵌入式linux
(Charon)7 小时前
【C++/Qt】Qt 实现 TCP Client:从功能构思到消息收发与日志保存
qt·网络协议·tcp/ip
qq_283720057 小时前
Qt5.12.8 QML Canvas ctx.setLineDash 失效终极解决方案
开发语言·qt
Z文的博客7 小时前
嵌入式LINUX QT 开发 .gitignore 文件编写指南
linux·git·qt·elasticsearch·嵌入式
掘根7 小时前
【微服务即时通讯】客户端数据中心
qt·微服务·架构
西门吹牛8 小时前
Pycharm编译器中部署了pyqt5,Qtdesigner无法打开了,解决方案
ide·qt·pycharm
buhuizhiyuci8 小时前
[QT]QT入门的项目创建和项目代码的介绍
开发语言·qt