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

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

相关推荐
Source.Liu2 小时前
【QOwnNotes】QOwnNotes 介绍
qt
特立独行的猫a2 小时前
QT开发鸿蒙PC应用:环境搭建及第一个HelloWorld
开发语言·qt·harmonyos·环境搭建·鸿蒙pc
零小陈上(shouhou6668889)5 小时前
YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)
python·qt·yolo
Larry_Yanan5 小时前
Qt多进程(五)QUdpSocket
开发语言·c++·qt·学习·ui
ht巷子6 小时前
Qt:容器类的迭代
开发语言·c++·qt
byxdaz7 小时前
Qt 中将 QWidget 改为模态的方法
qt
世转神风-10 小时前
qt-通信协议基础-QStirng转QByteArray-与字节序互动
开发语言·qt
特立独行的猫a11 小时前
QT开发鸿蒙PC应用:第一个Qt Widget应用入门
数据库·qt·harmonyos·鸿蒙pc·qtwidget
深蓝海拓12 小时前
PySide6从0开始学习的笔记(十八) MVC(Model-View-Controller)模式的图形渲染体系
笔记·python·qt·学习·pyqt
世转神风-12 小时前
qt-通信协议基础-固定长度-小端字节序补0x00指导
开发语言·qt