【问题标题】:Bind CheckBox checked-state in TableView to custom model attribute将 TableView 中的 CheckBox 选中状态绑定到自定义模型属性
【发布时间】:2026-02-16 02:45:01
【问题描述】:

我有一个 QML 应用程序,其中包含一个包含两列的 TableView。其中之一是复选框。现在我创建了一个从 QAbstractTableModel 派生的模型。读取普通文本列的数据已经可以了,但是如何将 CheckBox 的选中属性与模型同步?

目前我什至无法通过模型检查它。您可以在下面找到相关代码。

tablemodel.cpp

TableModel::TableModel(QObject *parent) :
QAbstractTableModel(parent)
{
   list.append("test1");
   list.append("test2");
}

int TableModel::rowCount(const QModelIndex &parent) const
{
   Q_UNUSED(parent);
   return list.count();
}

int TableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 2;
}

QVariant TableModel::data(const QModelIndex & index, int role) const {

if (index.row() < 0 || index.row() >= list.count())
    return QVariant();

if (role == NameRole)
    return list[index.row()]

else if (role== EnabledRole){
   //list is not QList<QString>, its a custom class saving a String and a boolean for the checked state
   return list[index.row()].isEnabled();
   }
   else {
      return QVariant();
   }
}

QHash<int, QByteArray> TableModel::roleNames() const {
   QHash<int, QByteArray> roles;
   roles[NameRole] = "name";
   roles[EnabledRole] = "enabled";
   return roles;
}

tablemodel.hpp

class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum Roles {
   NameRole = Qt::UserRole + 1,
   EnabledRole
};

explicit TableModel(QObject *parent = 0);

int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex & parent = QModelIndex()) const;
Q_INVOKABLE QVariant data (const QModelIndex & index, int role) const;

protected:
   QHash<int, QByteArray> roleNames() const;
private:
   QList<QString> list;

main.qml

TableView {

   id: Table
   model:  TableModel

   TableViewColumn {
      role: "name"
   }

   TableViewColumn {
      role: "enabled"
      delegate: CheckBox {
         //how to get the right state from the model
         //checked: ??
      }
   }
}

main.cpp

QQmlApplicationEngine engine;
QQmlContext * context = new QQmlContext(engine.rootContext());

TableModel tableModel;
context->setContextProperty("tableModel",&tableModel);

QQmlComponent component(&engine, QUrl("qrc:///main.qml"));
QQuickWindow * window = qobject_cast<QQuickWindow*>(component.create(context));
window->show();

【问题讨论】:

    标签: c++ qt tableview qml qt5.3


    【解决方案1】:

    点击复选框时,您可以从 qml 发出信号;将此信号连接到您的模型插槽并做一些事情

    main.qml

    TableView {
    id: table
    objectName: "myTable"
    signal checkedChanged(int index, bool cheked)
    TableViewColumn {
      role: "enabled"
      delegate: CheckBox {
         onClicked: table.checkedChanged(styleData.row, checked);
      }
    }
    

    main.cpp

    QQuickItem *obj = engine.rootObjects().at(0)->findChild<QQuickItem*>(QStringLiteral("myTable"));
    QObject::connect(obj,SIGNAL(checkedChanged(int,bool)),tableModel,SLOT(mySlot(int,bool)));
    

    【讨论】:

      最近更新 更多