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

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

相关推荐
上海安当技术13 小时前
C/S 桌面软件怎么接 UKey 强认证?C# SDK 与 C 动态库集成 WinForms/Qt/工控实战
c语言·qt·c#
雨田言炎15 小时前
五、Qt控件使用说明大全
开发语言·qt
熬夜苦读学习16 小时前
Qt--界面优化
开发语言·qt
Bryce学亮17 小时前
FileLine,基于 Qt 6 + QML 构建的跨平台文件传输与即时通讯工具
数据库·c++·人工智能·python·qt·github
sycmancia21 小时前
Qt——复习篇painter
开发语言·qt
Quz1 天前
QML ProgressBar 基础用法:默认样式与平滑动画
qt
繁重的秋春1 天前
Qt6.0下的CMake的部署配置
qt·cmake
qq_401700411 天前
Qt 程序启动太乱?重新设计你的 Application 生命周期
开发语言·qt
Quz1 天前
QML Tumbler 自定义滚轮:用 PathView 实现横向选择器
qt
Quz2 天前
QML Tumbler 样式定制:渐变、高亮与 3D 滚轮效果
qt