Qt Quick TableViews examples - Pixelator

Image non disponible

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

 
Sélectionnez
class ImageModel : public QAbstractTableModel
{
    Q_OBJECT
    Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged)
public:
    ImageModel(QObject *parent = nullptr);

    QString source() const;
    void setSource(const QString &source);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

    QVariant headerData(int /* section */, Qt::Orientation /* orientation */,
                        int role) const override;

signals:
    void sourceChanged();

private:
    QString m_source;
    QImage m_image;
};

We only require a simple, read-only table model. Thus, we need to implement functions to indicate the dimensions of the image and supply data to the TableView. We use the Qt Property System and a source property as QString to set the path of the image.

 
Sélectionnez
void ImageModel::setSource(const QString &source)
{
    if (m_source == source)
        return;

    beginResetModel();
    m_source = source;
    m_image.load(m_source);
    endResetModel();
}

Here we load the image when the source path is set. When the source path has changed, we need to call beginResetModel() before. After the image has been loaded, we need to call endResetModel().

 
Sélectionnez
int ImageModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_image.height();
}

int ImageModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_image.width();
}

The row and column count is set to image height and width, respectively.

 
Sélectionnez
QVariant ImageModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || role != Qt::DisplayRole)
        return QVariant();
    return qGray(m_image.pixel(index.column(), index.row()));
}

This overloaded function allows us to access the pixel data from the image. When we call this function with the display role, we return the pixel's gray value.

 
Sélectionnez
qmlRegisterType