alex_lip
alex_lip1. März 2018 07:25

Редактирование элемента QAbstractListModel

Есть модель, в которой 3 поля. 2 поля staffid, fio - не редактируются, а одно - chk - хочется редактировать через QML

Модель пытаюсь реализовать так

#ifndef MODEL_ISPOL_H
#define MODEL_ISPOL_H
#include <QAbstractListModel>
#include <QStringList>

//![0]
class Ispol
{
public:
    Ispol(const QString &staffid, const QString &fio, qint8 &chk);
//![0]

    QString staffid() const;
    QString fio() const;
    qint8 chk();

public:
    QString m_staffid;
    QString m_fio;
    qint8 m_chk;

//![1]
};

class IspolModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum IspolRoles {
        staffidRole = Qt::UserRole + 1,
        fioRole, chkRole
    };
    IspolModel(QObject *parent = 0);
//![1]

    virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
  //  virtual Qt::ItemFlags flags(const QModelIndex &index) const;

    void addIspol(const Ispol &Ispol);
    int rowCount(const QModelIndex & parent = QModelIndex()) const;
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
    void clearIspol();

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Ispol> m_Ispol;
//![2]
};
//![2]

#endif // MODEL_ISPOL_H

#include "model_ispol.h"

Ispol::Ispol(const QString &staffid, const QString &fio,  qint8 &chk)
: m_staffid(staffid), m_fio(fio), m_chk(chk)
{
}

QString Ispol::staffid() const
{
    return m_staffid;
}
QString Ispol::fio() const
{
    return m_fio;
}

qint8 Ispol::chk()
{
    return m_chk;
}

IspolModel::IspolModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void IspolModel::addIspol(const Ispol &Ispol)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_Ispol << Ispol;
    endInsertRows();
}

void IspolModel::clearIspol()
{
    beginRemoveRows(QModelIndex(), 0, rowCount()-1);
    while (!m_Ispol.isEmpty())
    {
        m_Ispol.removeLast();
    }
    endRemoveRows();
}

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


bool IspolModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid()) {
        return false;
    }
const Ispol &Ispol = m_Ispol[index.row()];
    switch (role) {
    case staffidRole:
        return false;   // This property can not be set
    case fioRole:
        return false;   // This property can not be set

    case chkRole:
        Ispol.m_chk = value.toInt();
        break;
        default:
        return false;
    }

    emit dataChanged(index, index, QVector<int>() << role);

    return true;
}

//Qt::ItemFlags IspolModel::flags(const QModelIndex &index) const
//{
//    if (!index.isValid())
//        return Qt::ItemIsEnabled;

//    return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
//}


QVariant IspolModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_Ispol.count())
        return QVariant();

    const Ispol &Ispol = m_Ispol[index.row()];
 if (role == staffidRole)
        return Ispol.staffid();
  else if (role == fioRole)
        return Ispol.fio();
 else if (role == chkRole)
       return Ispol.chk();
    return QVariant();
}

//![0]
QHash<int, QByteArray> IspolModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[staffidRole] = "staffid";
    roles[fioRole] = "fio";
    roles[chkRole] = "chk";
    return roles;
}
//![0]

Когда все было только чтение - все работало. Я попытался переопределить
bool IspolModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid()) {
        return false;
    }
const Ispol &Ispol = m_Ispol[index.row()];
    switch (role) {
    case staffidRole:
        return false;   // This property can not be set
    case fioRole:
        return false;   // This property can not be set

    case chkRole:
        Ispol.m_chk = value.toInt();
        break;
        default:
        return false;
    }

Ругается что 'Ispol::m_chk' in read-only object    Ispol.m_chk = value.toInt(); и
passing 'const Ispol' as 'this' argument discards qualifiers [-fpermissive] return Ispol.chk();
in call to 'qint8 Ispol::chk()'qint8 Ispol::chk()




Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

4
Evgenii Legotckoi
  • 1. März 2018 07:28

Потому, что Вы определили эту ссылку как константную.

const Ispol &Ispol
Правильно будет убрать const
Ispol &Ispol
Подробнее о константах
    alex_lip
    • 1. März 2018 07:58

    теперь ругается здесь

    QVariant IspolModel::data(const QModelIndex & index, int role) const {
        if (index.row() < 0 || index.row() >= m_Ispol.count())
            return QVariant();
    
         Ispol &Ispol = m_Ispol[index.row()];
     if (role == staffidRole)
            return Ispol.staffid();
      else if (role == fioRole)
            return Ispol.fio();
     else if (role == chkRole)
           return Ispol.chk();
        return QVariant();
    }

    ошибка: binding 'const Ispol' to reference of type 'Ispol&' discards qualifiers
    Ispol &Ispol = m_Ispol[index.row()];
    ^




      Evgenii Legotckoi
      • 1. März 2018 08:05

      Ну вот смотрите, у вас есть методы с const на конце и без const на конце. В зависимости от этого, они могут изменять данные, или не могут.

      соответсвенно, если есть в методе const на конце, то некоторые переменные потребуют const, внутри методов, а некоторые нет.

      Полагаю, что в setData вам не нужен const, а в data нужен.
        alex_lip
        • 1. März 2018 08:06

        Спасибо.

          Kommentare

          Nur autorisierte Benutzer können Kommentare posten.
          Bitte Anmelden oder Registrieren
          Letzte Kommentare
          A
          ALO1ZE19. Oktober 2024 08:19
          Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
          ИМ
          Игорь Максимов5. Oktober 2024 07:51
          Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
          d
          dblas55. Juli 2024 11:02
          QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
          k
          kmssr8. Februar 2024 18:43
          Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
          Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
          Jetzt im Forum diskutieren
          J
          JacobFib17. Oktober 2024 03:27
          добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
          JW
          Jhon Wick1. Oktober 2024 15:52
          Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
          КГ
          Кирилл Гусарев27. September 2024 09:09
          Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
          F
          Fynjy22. Juli 2024 04:15
          при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

          Folgen Sie uns in sozialen Netzwerken