1.与数据库连接,读取数据库内容到UI界面显示
// 连接SQLite数据库
db = QSqlDatabase::addDatabase("QSQLITE","second");
db.setDatabaseName("./testitem.db"); // 替换为你的数据库文件路径
if (!db.open()) {
qDebug() << "Failed to connect to database";
return;
}else
qDebug()<<"连接数据库成功"<<endl;
// 创建数据模型 /* QSqlQueryModel 适合用于查询数据,不能修改数据 */
dbmodel = new QSqlTableModel(this, db);
dbmodel->setTable("order_settings"); // 替换为你的表名 第一页订单号
/* 如果有修改则同步修改到数据库,
* 注意这个规则需要与 tabview 这样的控件才生效,
* 因为 tabview 可以直接编辑表里的内容 */
dbmodel->setEditStrategy(QSqlTableModel::OnFieldChange);
dbmodel->select();
// if(!dbmodel->select())
// qDebug()<<"err"<<endl;
mProxyModel = new QRowsLimitProxyModel;
mProxyModel->setSourceModel(dbmodel); //排序 筛选功能
mProxyModel->setDynamicSortFilter(true);
/* 设置表格的头信息,若不设置则显示数据库里的英文字段头信息 */
dbmodel->setHeaderData(dbmodel->fieldIndex("order_num"),
Qt::Horizontal, tr("订单号"));
dbmodel->setHeaderData(dbmodel->fieldIndex("tested_product_type"),
Qt::Horizontal, tr("被测品类型"));
dbmodel->setHeaderData(dbmodel->fieldIndex("inspect_unit"),
Qt::Horizontal, tr("送检单位"));
dbmodel->setHeaderData(dbmodel->fieldIndex("test_number"),
Qt::Horizontal, tr("试验编号"));
// 将查询结果绑定到TableView上
ui->tableView->setModel(mProxyModel);
}
2.读取到的内容设置居中对齐,需要重写QStyledItemDelegate类
方法一:
class CenterAlignedDelegate : public QStyledItemDelegate
{
public:
CenterAlignedDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
opt.displayAlignment = Qt::AlignCenter; // 设置对齐方式为居中
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter);
}
};
方法二:
class CenteredDelegate : public QStyledItemDelegate {
public:
CenteredDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
// 清除背景(如果需要)
painter->fillRect(opt.rect, opt.palette.background());
// 计算文本居中显示的起始位置
QRect textRect = opt.rect;
int textFlags = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip;
// 绘制居中的文本
QApplication::style()->drawItemText(painter, textRect, textFlags, opt.palette, true, opt.text);
}
};
在需要的地方引用这个重写类
// 设置内容居中显示
CenterAlignedDelegate *delegate = new CenterAlignedDelegate(this);
ui->tableView->setItemDelegate(delegate);