Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

New in Qt 5.11: improvements to the model/view APIs (part 2)

Automated validity checks using QAbstractItemModelTester

QAbstractItemModelTester *tester = new QAbstractItemModelTester(modelToTest);
// keep the tester object around; it will run a series of tests on modelToTest
class StringListModel : public QAbstractListModel {
    Q_OBJECT
public:
    using QAbstractListModel::QAbstractListModel;
    int rowCount(const QModelIndex &parent) const override {
        Q_ASSERT(checkIndex(parent));
        if (parent.isValid())
            return 0;
        return m_strings.size();
    }
    QVariant data(const QModelIndex &index, int role) const override {
        Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));
        if (role != Qt::DisplayRole)
            return {};
        return m_strings[index.row()];
    }
    // appends the string at the end of the model
    void appendString(const QString &string) {
        beginInsertRows(QModelIndex(), m_strings.size(), m_strings.size() + 1);
        m_strings.append(string);
        endInsertRows();
    }
private:
    QStringList m_strings;
};
// correct call: adds 1 row, at position m_strings.size()
 beginInsertRows(QModelIndex(), m_strings.size(), m_strings.size());
auto model = new StringListModel;
auto tester = new QAbstractItemModelTester(model,
                      QAbstractItemModelTester::FailureReportingMode::Warning);
FAIL! Compared values are not the same:
   Actual (model->rowCount(parent)) 1
   Expected (c.oldSize + (end - start + 1)) 2
   (qabstractitemmodeltester.cpp:669)

2 Comments

20 - Jul - 2022

Ali

22 - Jul - 2022

Giuseppe D'Angelo

find_package(Qt6 REQUIRED COMPONENTS Test)
target_link_libraries(your_app PRIVATE Qt6::Test)
GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer