I have the following code to align text of QTableWidget's column.
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QStyledItemDelegate
class AlignRightDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super(AlignRightDelegate, self).initStyleOption(option, index)
option.displayAlignment = Qt.AlignRight
class Table(QTableWidget):
def __init__(self, data, alignColumns = 1, *args):
QTableWidget.__init__(self, *args)
self.setRowCount(len(data))
self.setColumnCount(3)
self.setData(data)
self.resizeColumnsToContents()
for colIndex in range(1, 1 + alignColumns):
print("Align Column [", colIndex, "]", sep="")
self.setItemDelegateForColumn(colIndex, AlignRightDelegate())
def setData(self, data):
horizontalHeaders = []
for m, rowContent in enumerate(data):
for n, cellContent in enumerate(data[m]):
if (m == 0):
horizontalHeaders.append(cellContent)
else:
self.setItem(m - 1, n, QTableWidgetItem(cellContent))
self.setHorizontalHeaderLabels(horizontalHeaders)
if __name__ == "__main__":
data = [["col1", "col2", "col3"],
[ "1", "1", "a"],
[ "-1", "2", "b"],
[ "0", "3", "c"]]
print("python QTableWidgetAlignRight.py[ <AlignColumnCount=1]")
app = QApplication(sys.argv)
table = Table(data, int(sys.argv[1])) if (len(sys.argv) > 1) else Table(data)
table.show()
sys.exit(app.exec_())
If I execute the above code with python QTableWidgetAlignRight.py 1
it sort of works as it should as shown below with col2 aligned to the right but apparently to the top also:
However when I execute the same code with python QTableWidgetAlignRight.py 2
where I try to align 2 columns to the right, I ran into Python has stopped working error
. The following screenshot is actually on my Japanese Windows OS (Win 10 Pro 20H2 (OS Build 19402.1165))
However I searched the net for the same error message in English and I found a screenshot albeit not due to my code above (burrowed from this page: Python has stopped working).
So what is the correct way of aligning 2 columns of my QTableWidget (without an error and without aligning to the top vertically)? Also is this a bug in PyQt5?
For your information, I am using the following: Python 3.7.6
, conda 4.8.2
, pyqt 5.9.2 py37h6538335_2
. For column alignment, I looked at this for reference: How to align all items in a column to center in QTableWidget