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

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

相关推荐
千疑千寻~5 分钟前
【Qt】QT的程序打包
开发语言·qt
莫小墨31 分钟前
基于TCP/IP和UDP组播的Qt网络直播间项目
网络·qt·tcp/ip·udp
蓝天智能5 小时前
Qt 的字节序转换
开发语言·qt
jf加菲猫10 小时前
第2章 Hello World
开发语言·c++·qt·ui
laplace012311 小时前
PyQt5 + Qt Designer配置指令
开发语言·qt
奇树谦13 小时前
Qt 自定义菜单栏 / 工具栏按钮 QToolButton + InstantPopup 详细解析
开发语言·数据库·qt
QT 小鲜肉13 小时前
【C++基础与提高】第十一章:面向对象编程进阶——继承与多态
java·linux·开发语言·c++·笔记·qt
四维碎片13 小时前
【Qt】多线程学习笔记
笔记·qt·学习
TravisBytes14 小时前
一次 Qt 网络程序诡异崩溃排查:从 Breakpad 堆栈到 lambda 捕获悬空引用
网络·qt·php
碰大点15 小时前
数据库“Driver not loaded“错误,单例模式重构方案
数据库·sql·qt·单例模式·重构