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

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

相关推荐
YouEmbedded1 小时前
解码信号与槽(含 QTimer 应用)
qt·定时器·信号与槽
小灰灰搞电子1 小时前
Qt SCXML 模块详解
开发语言·qt
开始了码2 小时前
UDP 协议详解与 Qt 实战应用
qt·网络协议·udp
深蓝海拓16 小时前
PySide6从0开始学习的笔记(三) 布局管理器与尺寸策略
笔记·python·qt·学习·pyqt
꧁坚持很酷꧂17 小时前
Windows安装Qt Creator5.15.2(图文详解)
开发语言·windows·qt
淼淼76318 小时前
QT表格与数据
开发语言·qt
小灰灰搞电子19 小时前
Qt 实现炫酷锁屏源码分享
开发语言·qt·命令模式
追烽少年x20 小时前
Qt面试题合集(二)
qt
零小陈上(shouhou6668889)20 小时前
YOLOv8+PyQt5玉米病害检测系统(yolov8模型,从图像、视频和摄像头三种路径识别检测)
python·qt·yolo
蓝天智能21 小时前
QT实战:qrc资源动态加载
qt