C++ 向QML公开C++;
我试图通过C++ 向QML公开C++;,c++,qt,qml,qt-creator,qqmllistproperty,C++,Qt,Qml,Qt Creator,Qqmllistproperty,我试图通过Q\u可调用的QStringList availableport()函数从我在main类中直接向QML公开的类中公开QSerialPort.available() Main: qmlRegisterType<SerialPortManager>("com.MyApp.qml", 1, 0, "SerialPortManager"); 那么我该如何解决这个问题呢?一个解决方案是按照的建议返回一个QVariant,为此我们使用QVariant::fromValue() \if
Q\u可调用的QStringList availableport()
函数从我在main
类中直接向QML公开的类中公开QSerialPort.available()
Main:
qmlRegisterType<SerialPortManager>("com.MyApp.qml", 1, 0, "SerialPortManager");
那么我该如何解决这个问题呢?一个解决方案是按照的建议返回一个
QVariant
,为此我们使用QVariant::fromValue()
\ifndef SERIALPORTMANAGER\u H
#定义串行端口管理器
#包括
#包括
#包括
类SerialPortManager:公共QObject
{
Q_对象
公众:
Q_可调用的静态QVariant AvailableReports(){
QList portsavaailable=QSerialPortInfo::availableport();
QStringList名称可供选择;
for(常量QSerialPortInfo和端口信息:端口可用){
names\u portsavaailable一种解决方案是按照的建议返回一个QVariant
,为此,我们使用QVariant::fromValue()
\ifndef SERIALPORTMANAGER\u H
#定义串行端口管理器
#包括
#包括
#包括
类SerialPortManager:公共QObject
{
Q_对象
公众:
Q_可调用的静态QVariant AvailableReports(){
QList portsavaailable=QSerialPortInfo::availableport();
QStringList名称可供选择;
for(常量QSerialPortInfo和端口信息:端口可用){
names\u Portsavaailable不幸的是,我仍然得到了同样的错误。即使现在它是QVariant
类型。@ApostolisanAstassiou有多奇怪,我刚刚测试了它,试试我的代码:@ApostolisanAstassiou我怀疑ComboBox,QtQuick的哪个版本。你在使用控件?@ApostolisanAstassiou qml不做数据转换,qml不是js@Apostolisansastasiou我建议您将项目的每个功能都变成另一个小项目,当它可行时,当您在主项目中实现它时,您也将节省大量时间。:Dun幸运的是,我仍然得到同样的错误。即使现在它是QVariant
类型。@Apostolisansastasiou多么奇怪,我只是t测试它,请尝试我的代码:@ApostolisAnastasiou我怀疑ComboBox,QtQuick的哪个版本。您使用的控件?@ApostolisAnastasiou qml不进行数据转换,qml不进行数据转换js@ApostolisAnastasiou我建议您在ma中实现项目的每个功能时,将其作为一个小项目在项目中,您也将节省大量时间。:D
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;
}
ComboBox {
model: serial.availablePorts()
}
SerialPortManager {
id: serial
}
#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