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

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

相关推荐
程与留14 小时前
12_常用控件速查(下):QSpinBox、QSlider、QProgressBar、QCheckBox
c++·qt
秋田君21 小时前
QT_HTTP协议编程
qt·http·iphone
码农客栈21 小时前
Qt 打包为可执行文件发布
qt
布莱克6052 天前
单例模式详解:什么是单例模式,它能解决哪些问题?
开发语言·qt·单例模式
qq762118222 天前
windows Qt mingw 编译libzip
开发语言·windows·qt
skr爱码士2 天前
10_Qt Designer 与 UI 文件(.ui 原理、uic 编译、动态加载)
c++·qt·ui·客户端
IT爱学堂2 天前
QT原理与源码分析可以学到什么 QT视频课程 QT课程推荐 最新推荐
开发语言·qt
躺着听Jay2 天前
QT交叉编译
开发语言·qt
Quz2 天前
QML 焦点导航:Tab 顺序与方向键移动
qt
程与留2 天前
11_常用控件速查(上):QPushButton、QLabel、QLineEdit、QComboBox
c++·qt