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

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

相关推荐
龚建波19 小时前
《QDebug 2025年12月》
qt
特立独行的猫a1 天前
HarmonyOS鸿蒙PC开源QT软件移植:基于 Qt Widgets 的网络调试助手工具
qt·开源·harmonyos·鸿蒙pc
世转神风-1 天前
qt-通信协议基础-uint64_t转QByteArray-小端系统
开发语言·qt
世转神风-1 天前
qt-uint64_t转QByteArray小端字节序并指定长度-小端系统
qt
lxmyzzs1 天前
解决Ubuntu中OpenCV报错:Qt平台插件“xcb”加载失败(apt安装方案实测有效)
qt·opencv·ubuntu
我可以将你更新哟1 天前
【pyqt-1】把Qt Designer集成到pyCharm,PyQT(窗口、添加空控件、事件处理)
qt·pycharm·pyqt
会飞的胖达喵2 天前
Qt自动信号槽连接机制:深入解析与应用实践
开发语言·qt
Lhan.zzZ2 天前
Qt跨线程网络通信:QSocketNotifier警告及解决
开发语言·c++·qt
Aevget2 天前
QtitanDocking 如何重塑制造业桌面应用?多视图协同与专业界面布局实践
c++·qt·界面控件·ui开发·qtitandocking
qq_401700412 天前
QUdpSocket---单播
qt