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

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

相关推荐
mabing99314 小时前
Qt QMessageBox、QDialogButtonBox中英文翻译动态切换
开发语言·qt
秋田君15 小时前
QT_QColorDialog颜色对话框
java·数据库·qt
秋田君15 小时前
QT_QT布局常用类QSplitter窗口分割类与QDockWidget窗口停靠类
开发语言·数据库·qt
Lhan.zzZ16 小时前
深入理解 windeployqt:混合 C++/Qt 项目的打包指南
开发语言·c++·qt
Lhan.zzZ17 小时前
QML 开发中的“陷阱”:动态模型更新时,ComboBox 索引为何总是失效?
开发语言·qt
咯哦哦哦哦18 小时前
qt creator x86交叉编译arm 配置
开发语言·qt
秋田君19 小时前
QT_QT布局常用类QStackedWidget与QLayout类
开发语言·qt
用户8402409736081 天前
使用 PyQt5 打造功能完备的 PDF 编辑器:从设计到实现全解析
qt
Quz2 天前
QML RangeSlider 组件:范围选择与双滑块样式
qt
luoyayun3612 天前
【Qt for Harmony】 Qt 5.12.12 鸿蒙版 Windows 交叉编译
qt·harmonyos·qt for harmony