How to align data in QTableView?
-
Hello. I have my table view with QAbstractTableModel and I want to align all the data to the right. How can I do it?
I found several tutorials on this topic, but all of them reimplementdata()
method which I use for returning data of the model. Am I misunderstanding the method or is there a way to do it in some another way? -
@CuriousPan
You are misunderstanding the full power/usage of QVariant QAbstractItemModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const. Go look at that, and at enum Qt::ItemDataRole.Qt infrastructure calls the
data()
method multiple times to render each data item. It does so by passing in different values for therole
parameter. Your job is to write aswitch
statement looking atrole
s value and return different types of information. When it is called with the (default)Qt::DisplayRole
(orQt::EditRole
), and only then, you should return your item's data value. When it is called withQt::TextAlignmentRole
you should return your desired right-alignment value. -
@JonB. Thank you for the answer. I defenitely should read the documentation better.
Now I have one more question - I align data to the right, but it's in the right edge. Is there a way to align it to the right and vertically to the center?
-
@CuriousPan, found an answer to my question. Thank you.
-
@CuriousPan
:)While you are looking at enum Qt::ItemDataRole, see what other roles are defined. You can affect fonts, colors, tooltips.... You can also look at the passed-in
QModelIndex
and/or the type ofQVariant
returned fromQt::DisplayRole
/EditRole
to selectively return different values for these, e.g. only numbers should be right-aligned, strings should be left-aligned.