gpt4 book ai didi

c++ - 从 C++ 向 QML 公开串口名称

转载 作者:行者123 更新时间:2023-11-27 23:48:49 26 4
gpt4 key购买 nike

我正在尝试通过 Q_INVOKABLE QStringList availablePorts() 函数从我在 main 类中直接公开给 QML 的类中公开 QSerialPort.available()。

主要:

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

关于c++ - 从 C++ 向 QML 公开串口名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com