在C++和QML之间进行交互时,对delegate委托的注意事项:
C++中的模型:
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
enum MyRoles {
NameRole = Qt::UserRole + 1,
AgeRole
};
MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
private:
QList<QPair<QString, int>> m_data;
};
在QML中使用该模型:
ListView {
id: listView
model: myModel
delegate: Rectangle {
width: listView.width
height: 50
color: index % 2 === 0 ? "lightblue" : "white"
Text {
text: name
font.bold: true
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
padding: 10
}
Text {
text: age
font.bold: true
anchors.verticalCenter: parent.verticalCenter
anchors.right: parent.right
padding: 10
}
}
}
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(int age READ age WRITE setAge NOTIFY ageChanged)
public:
explicit MyDelegate(QObject *parent = nullptr);
QString name() const;
void setName(const QString &name);
int age() const;
void setAge(int age);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
signals:
void nameChanged();
void ageChanged();
private:
QString m_name;
int m_age;
};
在QML中使用该委托:
ListView {
id: listView
model: myModel
delegate: MyDelegate {
name: model.name
age: model.age
}
}
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit MyDelegate(QObject *parent = nullptr);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
signals:
void itemClicked(int index);
private slots:
void onItemClicked();
private:
QPointer<QListView> m_listView;
};
ListView {
id: listView
model: myModel
delegate: MyDelegate {
Connections {
target: delegate
onItemClicked: {
console.log("Item clicked: " + index);
}
}
}
}
在处理大量数据时,需要注意委托的性能优化。例如,可以避免在委托中进行过多的计算或者频繁的数据操作,以提高程序的性能和响应速度。