Solved Image alignment in QTableview
-
Hi guys !
Do someone knows how to center a picture in a QTableview cell ?
Here is my code :QStandardItem *itemProfilClient = new QStandardItem(); itemProfilClient->setData(QVariant(insertClient._profil.scaled(200,200, Qt::KeepAspectRatio)), Qt::DecorationRole); itemProfilClient->setTextAlignment(Qt::AlignCenter); _model->setItem(2, 3, itemProfilClient);
The issue is that the picture (which is insertClient._profil (QPixmap)) is not centered in the cell, but aligned left.
Can somebody help me please ? 😊
-
@Match0um You cannot change the alignment of the image using the model, in this case the solution is to use a QProxyStyle:
class ProxyStyle: public QProxyStyle{ public: using QProxyStyle::QProxyStyle; QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget) const override{ QRect rect = QProxyStyle::subElementRect(subElement, option, widget); if(subElement == SE_ItemViewItemDecoration){ rect.moveCenter(option->rect.center()); } return rect; } };
view->setStyle(new ProxyStyle(view->style()));
-
@eyllanesc Thank you so much it works !
-
There is no real need to reimplement a proxy style, it can easily be done with a delegate:
class AlignPicCenterDelegate : public QStyledItemDelegate{ public: using QStyledItemDelegate::QStyledItemDelegate; protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { QStyledItemDelegate::initStyleOption(option,index); option->decorationAlignment = Qt::AlignCenter; } };
Then on your view you can call https://doc.qt.io/qt-5/qabstractitemview.html#setItemDelegate