Qt Quick TableViews examples - Pixelator▲
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.
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 &
amp;source);
int
rowCount(const
QModelIndex &
amp;parent =
QModelIndex()) const
override
;
int
columnCount(const
QModelIndex &
amp;parent =
QModelIndex()) const
override
;
QVariant data(const
QModelIndex &
amp;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.
void
ImageModel::
setSource(const
QString &
amp;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().
int
ImageModel::
rowCount(const
QModelIndex &
amp;parent) const
{
if
(parent.isValid())
return
0
;
return
m_image.height();
}
int
ImageModel::
columnCount(const
QModelIndex &
amp;parent) const
{
if
(parent.isValid())
return
0
;
return
m_image.width();
}
The row and column count is set to image height and width, respectively.
QVariant ImageModel::
data(const
QModelIndex &
amp;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.
qmlRegisterType