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

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

相关推荐
kaixin_learn_qt_ing12 小时前
Qt Model/View
qt
Quz13 小时前
QML MouseArea:鼠标拖拽与滚轮缩放
qt·qml
CHPCWWHSU15 小时前
DeepSeek-Harness-Qt将浏览器端Agent装入桌面应用
开发语言·qt
飘忽不定的bug19 小时前
ubuntu20.04交叉编译QT5.15.12(RK3562+ubuntu20.04)
linux·qt·ubuntu
秋田君1 天前
Qt_QMediaPlayer类与QMediaPlaylist类
开发语言·qt
mengzhi啊1 天前
QT程序界面自适应1080/2K/4K屏幕。qputenv或者setAttribute
qt
C++ 老炮儿的技术栈1 天前
Qt5 使用 QPainter 绘制阿基米德螺线
开发语言·c++·windows·qt·代码化
大丑哥2 天前
QT QML 中实现高亮功能
qt
小白不想画工图2 天前
银河麒麟V10系统安装QT5.12
linux·开发语言·qt·银河麒麟
mengzhi啊2 天前
QEventLoop loop配合loop.exec();替代while(1)。电脑cpu占用为0,使用while(1)cpu占用率100%
c++·qt