在C++和QML之间进行交互时,对delegate委托的注意事项:

1.模型和委托的绑定

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
        }
    }
}

2.在C++中,可以通过实现Q_PROPERTY来将委托中的属性与C++中的数据进行关联:

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
    }
}

3.在C++中,需要注意委托对象的生命周期管理,可以使用QPointer来进行对象的弱引用:

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;
};

4.在QML中,可以使用Connections来连接委托中的信号和槽:

ListView {
    id: listView
    model: myModel
    delegate: MyDelegate {
        Connections {
            target: delegate
            onItemClicked: {
                console.log("Item clicked: " + index);
            }
        }
    }
}

在处理大量数据时,需要注意委托的性能优化。例如,可以避免在委托中进行过多的计算或者频繁的数据操作,以提高程序的性能和响应速度。

12-15 11:03