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

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

相关推荐
_nirvana_w_11 小时前
Qt项目链接库时遇到的坑:-l选项的正确用法
开发语言·c++·qt·qt框架·elawidgettools
云泽80811 小时前
从图形界面到跨平台王者:Qt 客户端开发全解析
开发语言·qt
持梦远方11 小时前
QML 与 C++ 后端交互学习笔记
c++·qt·学习·交互
非得登录才能看吗?2 天前
Qt 的cmake与qmake
开发语言·qt
程序员敲代码吗2 天前
Qt Quick中QML与C++交互详解及场景切换实现
c++·qt·交互
only-lucky2 天前
Qt惯性动画效果
开发语言·qt
CodeByV2 天前
【Qt】常用控件
开发语言·qt
Real-Staok3 天前
QT & QML 总结备查
qt·ui·ux
CodeByV3 天前
【Qt】窗口
开发语言·qt
枫叶丹43 天前
【Qt开发】Qt界面优化(四)-> Qt样式表(QSS) 选择器概况
c语言·开发语言·c++·qt