本文主要是介绍Qt 小例子学习43 - c++ 把串口传给qml,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Qt 小例子学习43 - c++ 把串口传给qml
SerialPortManager.h
#ifndef SERIALPORTMANAGER_H
#define SERIALPORTMANAGER_H#include <QObject>
#include <QSerialPortInfo>
#include <QVariant>class SerialPortManager : public QObject
{Q_OBJECT
public:Q_INVOKABLE static QVariant availablePorts(){QList<QSerialPortInfo> portsAvailable = QSerialPortInfo::availablePorts();QStringList names_PortsAvailable;for (const QSerialPortInfo &portInfo : portsAvailable){names_PortsAvailable << portInfo.portName();}return QVariant::fromValue(names_PortsAvailable);}
};#endif // SERIALPORTMANAGER_H
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import com.MyApp.qml 1.0Window {visible: truewidth: 640height: 480title: qsTr("Hello World")ComboBox {model: serial.availablePorts()}SerialPortManager {id: serial}
}
main.cpp
#include "serialportmanager.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endifQGuiApplication app(argc, argv);qmlRegisterType<SerialPortManager>("com.MyApp.qml", 1, 0,"SerialPortManager");QQmlApplicationEngine engine;engine.load(QUrl(QStringLiteral("qrc:/main.qml")));if (engine.rootObjects().isEmpty())return -1;return app.exec();
}
这篇关于Qt 小例子学习43 - c++ 把串口传给qml的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!