you need to use a delegate to accomplish this. Overwrite the delegates paint
event with the following:
QAlignmentDelegate.h
#include <QStyledItemDelegate>
class QAlignmentDelegate : public QStyledItemDelegate
{
public:
explicit QAlignmentDelegate(Qt::Alignment alignment, QObject* parent = 0)
: QStyledItemDelegate(parent),
m_alignment(alignment)
{
}
virtual void QAlignmentDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QStyleOptionViewItem alignedOption(option);
alignedOption.displayAlignment = m_alignment;
QStyledItemDelegate::paint(painter, alignedOption, index);
}
private:
Qt::Alignment m_alignment; ///< Stores the alignment to use
};
Then simply assign the delegate to the view. In you mainWindow
class (or wherever you create or use the view), the delegate can be used as follows:
MainWindow code
#include "QAlignmentDelegate.h"
...
QAlignmentDelegate* myDelegate = new QAlignmentDelegate(Qt::AlignmentCenter);
QTableView* myTableView = new QTableView(this);
myTableView->setItemDelegate(myDelegate);
myTableView->setModel(...); // start using the view
You can specify whatever Qt::Alignment (or combination of them using OR) when you create the delegate.
Alternatively, if you wrote/control the model code, you can implement the Qt::AlignmentRole
and return 'Qt::AlignHCenter
for data you want to be cetner-aligned.