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 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
Larry_Yanan6 小时前
QML学习笔记(三十一)QML的Flow定位器
java·前端·javascript·笔记·qt·学习·ui
Larry_Yanan7 小时前
QML学习笔记(三十)QML的布局器(Layouts)
c++·笔记·qt·学习·ui
feiyangqingyun7 小时前
Qt编写上下界面切换效果/前进到下一个界面/后退到上一个页面/零件工艺及管理设计系统
qt·零件工艺
ajassi20007 小时前
开源 C++ QT QML 开发(十五)通讯--http下载
c++·qt·开源
枫叶丹49 小时前
【Qt开发】输入类控件(六)-> QDial
开发语言·qt
咯哦哦哦哦11 小时前
关于QT 打印中文 乱码问题
java·数据库·qt
mark-puls11 小时前
Qt界面布局利器:QStackedWidget详细用法解析
开发语言·qt
执尺量北斗15 小时前
LinkMate 智能会议室系统:基于 Qt / QML / WebRTC / FFmpeg / Whisper / OpenGL 的实时音视频会议平台
qt·ffmpeg·webrtc
共享家95271 天前
QT-常用控件(二)
开发语言·qt