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

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

相关推荐
AAA废品回收站陈师傅2 小时前
68常用控件_QGroupBox的使用
qt
明月醉窗台2 小时前
qt使用笔记二:main.cpp详解
数据库·笔记·qt
沉到海底去吧Go2 小时前
【图片自动识别改名】识别图片中的文字并批量改名的工具,根据文字对图片批量改名,基于QT和腾讯OCR识别的实现方案
数据库·qt·ocr·图片识别自动改名·图片区域识别改名·pdf识别改名
奥修的灵魂6 小时前
QT进阶之路:带命名空间的自定义控件在Qt设计器与qss中的使用技巧
qt·命名空间
笨笨马甲10 小时前
附加模块--Qt OpenGL模块功能及架构
开发语言·qt
uyeonashi14 小时前
【QT控件】输入类控件详解
开发语言·c++·qt
galaxy_strive1 天前
绘制饼图详细过程
开发语言·c++·qt
委婉待续1 天前
Qt的学习(一)
开发语言·qt·学习
笨笨马甲1 天前
Qt Quick Layout功能及架构
开发语言·qt
feiyangqingyun1 天前
Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动
c++·qt·udp·gb28181