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

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

相关推荐
小灰灰搞电子41 分钟前
Qt 二进制数据读写详解
开发语言·qt
小新1101 小时前
Qt 中安全拼接文件路径
开发语言·qt
X.Ming 同学1 小时前
QXlsx 库在麒麟 Linux(Qt 5.15.2)下完整安装步骤(含问题排查 & 经验总结)
linux·数据库·qt
chen_2271 小时前
qt加ffmpeg制作简易录屏工具
开发语言·qt·ffmpeg
踏过山河,踏过海2 小时前
【Qt VS Tools在Visual Studio 2019中不起作用的解决方法】
qt·visual studio
ht巷子2 小时前
Qt:容器类
开发语言·c++·qt
_OP_CHEN2 小时前
【从零开始的Qt开发指南】(十三)Qt 窗口之菜单栏完全攻略:从入门到实战,打造专业级桌面应用菜单系统
开发语言·qt·前端开发·图形化界面·菜单栏·gui开发·qt窗口
小c君tt14 小时前
QT中想在QTextEdit控件中使用Qslog日志输出出现问题原因及解决方法
开发语言·qt
SunkingYang16 小时前
QT程序怎么接收MFC通过sendmessage发送的信号
qt·mfc·信号·事件·sendmessage·接收消息
SunkingYang17 小时前
Qt中QString 查找子串的完整指南
qt·字符串·qstring·子字符串·查找子串