-
在Qt毫無疑問的是可以將自定義類型(struct/class)作為數(shù)據(jù)類型在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)
假設(shè)在C++發(fā)射信號如下:
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++傳遞自定義類型作為參數(shù)到Qml.gif
代碼工程在這里下載:
C++傳遞自定義類型作為參數(shù)到Qml