[英]Exposing to QML the serial port names from C++
我試圖通過Q_INVOKABLE QStringList availablePorts()
函數公開QSerialPort.available(),該函數來自直接在我的main
類中公開給QML的類。
主要:
qmlRegisterType<SerialPortManager>("com.MyApp.qml", 1, 0, "SerialPortManager");
串口管理器
class SerialPortManager : public QObject
{
Q_OBJECT
public slots:
Q_INVOKABLE virtual QStringList availablePorts() {
QList<QSerialPortInfo> portsAvailable = QSerialPortInfo::availablePorts();
QStringList names_PortsAvailable;
for(QSerialPortInfo portInfo : portsAvailable) {
names_PortsAvailable.append(portInfo.portName());
}
return names_PortsAvailable;
}
這對QML中的model
類型無效,因為它引發了Unable to assign QStringList to QQmlListModel*
錯誤。
QML
ComboBox {
model: serial.availablePorts()
}
SerialPortManager {
id: serial
}
那么我該如何解決呢?
一種解決方案是返回docs推薦的QVariant
,為此,我們使用QVariant::fromValue()
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.