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.

PyQt/PySide 1:1 Coaching with Martin Fitzpatrick — Get one on one help with your Python GUI projects. Working together with you I'll identify issues and suggest fixes, from bugs and usability to architecture and maintainability.

More info 60 mins ($195)

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'


Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PyQt6 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

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.