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

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

相关推荐
扶尔魔ocy1 天前
【QT window】multimedia+ffmpeg实现(PCM和MP4)录音功能
qt·ffmpeg·pcm
YouEmbedded1 天前
解码 Qt 交互:滑动交互、窗口拖拽
qt·滑动交互·上滑关闭·滑动显示 / 隐藏
郝学胜-神的一滴1 天前
使用EBO绘制图形:解锁高效渲染与内存节省之道
c++·qt·游戏·设计模式·系统架构·图形渲染
枫叶丹41 天前
【Qt开发】Qt事件(一)
c语言·开发语言·数据库·c++·qt·microsoft
刺客xs1 天前
Qt------信号槽,属性,对象树
开发语言·qt·命令模式
zxb@hny2 天前
配置beyondcompare合并git操作
qt
liangshanbo12152 天前
深入理解 Model Context Protocol (MCP):从原理到实践
开发语言·qt·microsoft
2739920292 天前
QT5使用QFtp
开发语言·qt
怪力左手2 天前
qt qspinbox editingfinished事件问题
开发语言·qt
我喜欢就喜欢2 天前
2025技术成长复盘:解决问题的365天
c++·qt