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

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

相关推荐
程序员爱钓鱼3 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt
无畏烧风4 小时前
[Qt] visual studio code 安装 Qt插件
qt
坏柠9 小时前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
雨落倾城夏未凉10 小时前
4.信号与槽
后端·qt
追风赶月、1 天前
【QT】事件(鼠标、按键、定时器、窗口)
qt
牵牛老人1 天前
Qt处理USB摄像头开发说明与QtMultimedia与V4L2融合应用
stm32·单片机·qt
-凌凌漆-1 天前
【Qt】QStringLiteral 介绍
开发语言·qt
想要入门的程序猿1 天前
Qt写入excel
数据库·qt·excel
丁劲犇1 天前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse
charlie1145141911 天前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析