QTableView Align Currency Column Right with QStyledItemDelegate

Heads up! You've already completed this tutorial.

Edward_Lipson | 2021-04-04 13:42:52 UTC | #1

How can I align the currency value in a column? QAbstractTableModel.data() just has strings to return so I get an error trying to .setAlignment() there. The delegate has no 'role' parm to align for display. The createEditor works ok with the QLineEdit().setAlignment(Qt.AlignRight).

Do I need to implement paint() for display of text?


PedanticHacker | 2021-04-05 09:15:33 UTC | #2

Maybe THIS will give you a hint.


Edward_Lipson | 2021-04-05 11:42:26 UTC | #3

I know that. If I use the QTableWidget (not my question here, I'm using QTableView/QAbstractTableModel with QStyledItemDelegate for editing) and set the QTableWidgetItem to the cell with setCellWidget, I can use the alignment of the QTableWidgetItem, along with a QValidator.

I'm trying to learn the Model/View concepts. I've got them working for what I need except for alignment.


PedanticHacker | 2021-04-05 11:49:23 UTC | #4

Can you try using setTextAlignment() instead of setAlignment()?


Edward_Lipson | 2021-04-05 13:01:58 UTC | #5

I kept on searching, and of course it was right in front of me (in the Book!) - Learpyqt qtableview modelview. It is part of the model, data() function .... elif role == Qt.TextAlignmentRole: if index.column() in (amt_columns): return Qt.AlignRight

For some reason it does not work correctly if I return Qt.AlignRight | Qt.AlighVCenter

Edited: read further on the page and saw Qt.AlignVCenter + Qt.AlignRight But: TypeError: unsupported operand type(s) for +: 'PySide2.QtCore.Qt.AlignmentFlag' and 'PySide2.QtCore.Qt.AlignmentFlag'


Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt5
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

QTableView Align Currency Column Right with QStyledItemDelegate was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.