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

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

相关推荐
非得登录才能看吗?10 小时前
Qt 的cmake与qmake
开发语言·qt
程序员敲代码吗11 小时前
Qt Quick中QML与C++交互详解及场景切换实现
c++·qt·交互
only-lucky1 天前
Qt惯性动画效果
开发语言·qt
CodeByV1 天前
【Qt】常用控件
开发语言·qt
Real-Staok1 天前
QT & QML 总结备查
qt·ui·ux
CodeByV1 天前
【Qt】窗口
开发语言·qt
枫叶丹42 天前
【Qt开发】Qt界面优化(四)-> Qt样式表(QSS) 选择器概况
c语言·开发语言·c++·qt
iCjMuKUypQs2 天前
北方苍鹰优化算法优化NGO - SVM分类模型:小白友好版教程
qt
草莓熊Lotso2 天前
Qt 核心事件系统全攻略:鼠标 / 键盘 / 定时器 / 窗口 + 事件分发与过滤
运维·开发语言·c++·人工智能·qt·ui·计算机外设
老歌老听老掉牙3 天前
QT开发踩坑记:按钮点击一次却触发两次?深入解析信号槽自动连接机制
c++·qt