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

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

相关推荐
深蓝海拓1 天前
PySide6从0开始学习的笔记(二十五) Qt窗口对象的生命周期和及时销毁
笔记·python·qt·学习·pyqt
从此不归路1 天前
Qt5 进阶【13】桌面 Qt 项目架构设计:从 MVC/MVVM 到模块划分
开发语言·c++·qt·架构·mvc
无小道1 天前
QT——简介
qt
xmRao1 天前
Qt+FFmpeg 实现音频重采样
qt·ffmpeg·音视频
专注echarts研发20年1 天前
如何实现 QLabel 的 Click 事件?Qt 富文本超链接优雅方案
开发语言·qt
小小码农Come on1 天前
QT控件之QTabWidget使用
开发语言·qt
Li_Zhi_Yao1 天前
linux下qt快速搭建环境
linux·运维·qt
从此不归路1 天前
Qt5 进阶【12】JSON/XML 数据协议处理:与后端/配置文件的对接
xml·开发语言·c++·qt·json
艾莉丝努力练剑1 天前
【QT】信号与槽
linux·开发语言·c++·人工智能·windows·qt·qt5
轩情吖1 天前
Qt的窗口(二)
开发语言·c++·qt·qdialog·对话框·桌面级开发