一、单元格内文字居中
CustomSqlQueryModel.h
#ifndef CUSTOMSQLQUERYMODEL_H
#define CUSTOMSQLQUERYMODEL_H
#include <QObject>
#include <QSqlQueryModel>
class CustomSqlQueryModel : public QSqlQueryModel
{
public:
CustomSqlQueryModel(QObject *parent = 0);
// QAbstractItemModel interface
public:
QVariant data(const QModelIndex &index, int role) const override;
};
#endif // CUSTOMSQLQUERYMODEL_H
CustomSqlQueryModel.cpp
#include "customsqlquerymodel.h"
CustomSqlQueryModel::CustomSqlQueryModel(QObject *parent) : QSqlQueryModel(parent)
{
}
/** * @brief 实现单元格内文字居中 */
QVariant CustomSqlQueryModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);
/** * 单元格内容居中 */
if (Qt::TextAlignmentRole == role) {
value = Qt::AlignCenter;
}
return value;
}
二、常用设置
//选择行为:行选择
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
//选择模式:单选(PS:还有一种模式是多选,按住 ctrl 多选)
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
//隔行变色
ui->tableView->setAlternatingRowColors(true);
//根据内容自动调整列宽
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//最后一行是否铺满剩余空间
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);