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

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

相关推荐
小温冲冲18 小时前
QtObject 详解:QML 中的轻量级数据容器
qt
huwei85319 小时前
Q打印表格内容类
开发语言·qt
Quz1 天前
QML 常用的基础容器组件(Pane、Frame、GroupBox、ScrollView 和 Page)
qt·交互
墨月白1 天前
[QT] QT中的折线图和散点图
数据库·qt
问水っ1 天前
Qt Creator快速入门 第三版 第16-7章 其他内容
开发语言·qt
Tianwen_Burning1 天前
qt控件QVTKOpenGLNativeWidget全窗口显示
qt·pcl·halcon3d
小CC吃豆子1 天前
Qt的信号与槽机制
开发语言·数据库·qt
qq_401700411 天前
Qt属性系统
开发语言·数据库·qt
默默前行的虫虫1 天前
QT、html中的大屏可视化带源码
qt
郝学胜-神的一滴1 天前
Qt实现圆角窗口的两种方案详解
开发语言·c++·qt·程序人生