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

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

相关推荐
我是菜鸟0713号19 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_19 小时前
QT(4)
开发语言·汇编·c++·qt·算法
lqjun08271 天前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞1 天前
Qt Designer与事件处理
开发语言·qt·命令模式
mkhase1 天前
9.12-QT-基本登陆界面实现
java·jvm·qt
咕噜咕噜啦啦1 天前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
Quz2 天前
QML Charts组件之折线图的鼠标交互
qt
眠りたいです2 天前
基于脚手架微服务的视频点播系统-数据管理与网络通信部分的预备工作
c++·qt·ui·微服务·云原生·架构·媒体
bikong72 天前
Qt/C++,windows多进程demo
c++·windows·qt
油炸自行车2 天前
【Qt】Window环境下搭建Qt6、MSVC2022开发环境(无需提前安装Visual Studio)
qt·visual studio·qt6·msvc2022·qt creator 17.0