cpp端
直接上代码
这是.h文件的内容,将对字符和字符串提供给qml
#ifndef DATA_BASE_H
#define DATA_BASE_H
#include "data_base.h"
#include <QObject>
#include <QStringList>
class DataModel : public QObject
{
Q_OBJECT
Q_PROPERTY(QStringList stringList READ stringList WRITE setStringList NOTIFY stringListChanged)
Q_PROPERTY(QString selectString READ SelectString WRITE SetSelectString NOTIFY SelectStringChange)
public:
explicit DataModel(QObject *parent = nullptr);
QStringList stringList() const ;
void setStringList(const QStringList &list);
QString SelectString() const;
void SetSelectString(const QString string);
signals:
void stringListChanged();
void SelectStringChange();
private:
QStringList stringList_;
QList< QStringList > list_;
QString selectString_;
};
#endif // DATA_BASE_H
这是cpp中的内容
#include "data_base.h"
#include <QDebug>
DataModel::DataModel(QObject *parent): QObject(parent)
{
stringList_ << "Item data1" << "Item data2" << "Item data3";
selectString_ = stringList_[1];
}
QStringList DataModel::stringList() const
{
return stringList_;
}
void DataModel::setStringList(const QStringList &list)
{
if (stringList_ == list) {
return;
}
stringList_ = list;
emit stringListChanged();
}
QString DataModel::SelectString() const
{
return selectString_;
}
void DataModel::SetSelectString(const QString string)
{
qDebug() << " cpp : change data str is: " << string;
selectString_ = string;
qDebug() << " cpp : selectString_ is : " << selectString_;
emit SelectStringChange();
}
qml端
import QtQuick
import QtQuick.Controls
import MyApp 1.0
// 创建一个包含多个字符串的 JavaScript 数组,并将其暴露给 QML
ComboBox {
editable: true
textRole: "text"
displayText: currentText + " >>> " + currentIndex
// model: [
// { value: Qt.NoModifier, text: qsTr("No modifier") },
// { value: Qt.ShiftModifier, text: qsTr("Shift") },
// { value: Qt.ControlModifier, text: qsTr("Control") }
// ]
//------------------显示Model方式1-----------------------------------------
// model: ListModel {
// id: model
// ListElement { text: "Banana" }
// ListElement { text: "Apple" }
// ListElement { text: "Coconut" }
// }
// ------------------显示Model方式2---------------------------
// 导入模块
DataModel {
id: dataModel
}
model:ListModel {
id: listModel
}
// 将 QStringList 数据写入 ListModel 中
Component.onCompleted: {
for (var i = 0; i < dataModel.stringList.length; ++i) {
listModel.append({ "text": qsTr(dataModel.stringList[i])})
}
currentIndex = indexOfValue(dataModel.selectString) // 找到数据对应的值
}
// 存在可能重复选中的情况
onAccepted: {
if (find(editText) === -1) {
// model.append({text: editText})
} else {
// 选中一个数据后,下发到后端
dataModel.selectString = currentValue
}
console.log(" editText data is ", editText);
}
onCurrentIndexChanged: {
// 选中一个数据后,下发到后端
// currentValue 是上一个选中数据的data
dataModel.selectString = dataModel.stringList[currentIndex]
console.log(currentValue + " index is:" + currentIndex, " data is:", currentValue)
}
}