Привязать проверенное состояние CheckBox в TableView к пользовательскому атрибуту модели

0

У меня есть QML-приложение, содержащее TableView с двумя столбцами. Один из них - CheckBox. Теперь я создал модель, полученную из QAbstractTableModel. Чтение данных для обычного текстового столбца уже работает, но как мне синхронизировать свойство check-check для моей CheckBox с моделью?

В настоящее время я даже не могу установить его через модель. Ниже вы найдете соответствующий код.

Изображение 174551

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();
Теги:
qt
tableview
qml
qt5.3

1 ответ

2

Вы можете испускать сигнал из 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)));

Ещё вопросы

Сообщество Overcoder
Наверх
Меню