-
在Qt毫无疑问的是可以将自定义类型(struct/class)作为数据类型在C++类之间传递,但是从C++传递自定义类型并且暴露属性给Qml就不行了,因为C++与Qml之间的信号传递只支持基本类型,具体可以参考Data Type Conversion Between QML and C++
具体参考如下代码(带注释的是注意事项,不支持从QObject派生,并不支持NOTIFY属性)
class CustomData /*: public QObject*/
{
Q_GADGET
Q_PROPERTY(QString filePath READ filePath WRITE setFilePath /*NOTIFY filePathChanged*/)
Q_PROPERTY(QString duration READ duration WRITE setDuration /*NOTIFY durationChanged*/)
Q_PROPERTY(QString fileName READ fileName WRITE setFileName /*NOTIFY fileNameChanged*/)
public:
explicit CustomData()
: m_filePath(""), m_fileName("") , m_duration("")
{}
CustomData(const CustomData &other)
{
m_filePath = other.m_filePath;
m_duration = other.m_duration;
m_fileName = other.m_fileName;
}
~CustomData() = default ;
QString filePath()
{
return m_filePath;
}
void setFilePath(QString filePath){
m_filePath = filePath;
//emit filePathChanged();
}
QString fileName()
{
return m_fileName;
}
void setFileName(QString fileName){
m_fileName = fileName;
//emit fileNameChanged();
}
QString duration()
{
return m_duration;
}
void setDuration(QString duration)
{
m_duration = duration;
//emit durationChanged();
}
//signals:
// void filePathChanged();
// void durationChanged();
// void indexsChanged();
// void fileNameChanged();
private:
QString m_filePath;
QString m_fileName;
QString m_duration;
};
Q_DECLARE_METATYPE(CustomData)
假设在C++发射信号如下:
Q_INVOKABLE void emitCustomData(){
CustomData data;
data.setFileName("bbbb");
data.setFilePath("aaa");
data.setDuration("cccc");
emit sigCustomData(data);
}
在Qml中接受信号
Connections{
target: DataVM
onSigCustomData:{
fileNameTex.text = "文件 : " +data.fileName;
filePathTex.text = "路径 : " + data.filePath;
durantionTex.text = "时间 : " + data.duration;
}
}
运行示例截图如下:
代码工程在这里下载:
C++传递自定义类型作为参数到Qml