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

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

相关推荐
小灰灰搞电子36 分钟前
Qt 输入验证入门:QValidator 类详解
开发语言·qt
凤年徐18 小时前
Qt 第三章 常用控件总结
开发语言·qt
草莓熊Lotso21 小时前
Qt 进阶控件实战:下拉框、列表、表格 + 旋钮 / 滑动条全攻略
大数据·c语言·开发语言·c++·人工智能·qt
迎風吹頭髮21 小时前
QT中使用QSqlTableModel快速展示SQLite3数据表(TableView实现)
开发语言·qt·sqlite
ShineWinsu1 天前
对于Qt:QMediaPlayer和QVideoWidget的解析
开发语言·c++·qt·视频·客户端·qmediaplayer·媒体播放器
li星野1 天前
Qt 单例配置管理器学习记录:JsonConfigManager 的设计原理与使用示例
开发语言·qt·学习
蓝蓝的代码人2 天前
用 Python、Qt 和 Vue 做一个 Windows 股票看盘工具,观潮的行情小窗与桌面提醒
vue.js·python·qt·开源·桌面应用
ShineWinsu2 天前
对于Qt:QSound的解析
c++·qt·面试·音频·笔试·客户端·qsound
小灰灰搞电子3 天前
QLibrary 类详解:在运行时与共享库对话
qt·qlibrary
敲上瘾3 天前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3