Qt QTableView居中
自定义代理实现表格数据居中
qtableview_delegate.h
#ifndef QTABLEVIEW_DELEGATE_H
#define QTABLEVIEW_DELEGATE_H
#include <QObject>
#include <QStyledItemDelegate>
class qtableview_delegate : public QStyledItemDelegate
{
public:
qtableview_delegate();
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
#endif // QTABLEVIEW_DELEGATE_H
qtableview_delegate.cpp
#include "qtableview_delegate.h"
qtableview_delegate::qtableview_delegate()
{
}
void qtableview_delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem new_option(option);
new_option.displayAlignment = Qt::AlignCenter; // 居中显示
if (new_option.state & QStyle::State_Selected) {
new_option.font.setBold(true); // 变为粗体
}
QStyledItemDelegate::paint(painter, new_option, index);
}
使用
qtableview_delegate * delegate = nullptr;
delegate = new qtableview_delegate;
ui->tableView->setItemDelegate(delegate);