新建QSqlTableModel类的子类,重写data函数,具体如下
头文件
#ifndef MYSQLTABLEMODEL_H
#define MYSQLTABLEMODEL_H
#include <QObject>
#include <QSqlTableModel>
class MySqlTableModel : public QSqlTableModel
{
public:
MySqlTableModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase());
void SetSelectColQuery(QString scq);
QVariant data(const QModelIndex &index, int role = Qt::TextAlignmentRole) const override;
protected:
QString selectStatement() const;
QString m_strSelectColQuery;
};
#endif // MYSQLTABLEMODEL_H
源文件:
#include "MySqlTableModel.h"
MySqlTableModel::MySqlTableModel(QObject *parent, QSqlDatabase db)
: QSqlTableModel(parent, db)
{
}
void MySqlTableModel::SetSelectColQuery(QString scq)
{
m_strSelectColQuery = scq;
}
QVariant MySqlTableModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);
if (Qt::TextAlignmentRole == role) {
value = Qt::AlignCenter;
}
return value;
}
QString MySqlTableModel::selectStatement() const
{
return m_strSelectColQuery;
}
但此时还应该注意到重写的函数data第二个参数默认值为int role = Qt::TextAlignmentRole,因此在具体用到data函数时应该根据具体需要明确输入role的值,比如获取某一单元格的值时应指定该参数的值为Qt::DisplayRole,代码为QString str = m_pTableModal->data(m_pTableModal->index(row, col), Qt::DisplayRole).toString();