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

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

相关推荐
ada0_ada115 小时前
qt模块学习记录
开发语言·qt·学习
knighthood200115 小时前
Qt5.15+VTK9.3.0实现点云点选功能
开发语言·qt
xyx-3v16 小时前
qt创建新工程
开发语言·c++·qt
大神的风范17 小时前
QT部署YOLO11实时检测
驱动开发·深度学习·qt·目标检测·计算机视觉
cpp_learner18 小时前
Linux ARM架构 使用 linuxdeployqt 打包QT程序
qt
泉飒18 小时前
C2001: 常量中有换行符-QT解决办法-逆向思路
开发语言·qt
泉飒19 小时前
QT的报错
qt
byxdaz20 小时前
QT中USB入门(QtUsb)
qt·qtusb
森G20 小时前
48、柱状图---------QChart
c++·qt
Larry_Yanan1 天前
Qt+OpenCV(一)环境搭建
开发语言·c++·qt·opencv·学习