0

I have the following issue.

I have a very simple code which is connecting to my local sql database, and from there I am exporting a data set with a query. Then I display this data in a PyQT table widget and that is all. The problem is that I cannot align my data to center of columns. Currently, everything is aligned to the left. I tried to use different combinations with Qt.AlignCenter but I cannot make it working.

here is my code

import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql


class BlobDelegate(QtWidgets.QStyledItemDelegate):
    def displayText(self, value, locale):
        if isinstance(value, QtCore.QByteArray):
            value = value.data().decode()
        return super(BlobDelegate, self).displayText(value, locale)


def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stats.db")
    db.setDatabaseName(file)
    if not db.open():
        QtWidgets.QMessageBox.critical(
            None,
            QtWidgets.qApp.tr("Cannot open database"),
            QtWidgets.qApp.tr(
                "Unable to establish a database connection.\n"
                "This example needs SQLite support. Please read "
                "the Qt SQL driver documentation for information "
                "how to build it.\n\n"
                "Click Cancel to exit."
            ),
            QtWidgets.QMessageBox.Cancel)
        return False
    return True


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    if not createConnection():
        sys.exit(-1)
    w = QtWidgets.QTableView()
    w.setFont(QtGui.QFont('Arial', 18))
    w.horizontalHeader().setStretchLastSection(False)
    w.horizontalHeader().setFixedHeight(40)
    w.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
    # w.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
    w.setWordWrap(True)
    delegate = BlobDelegate(w)
    w.setItemDelegateForColumn(4, delegate)
    model = QtSql.QSqlQueryModel()
    model.setQuery("SELECT * FROM table_tennis_statistics")
    w.setModel(model)
    w.resize(1024, 600)
    w.show()
    sys.exit(app.exec_())


screenshot

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

1

You have to modify the displayAlignment property of QStyleOptionViewItem and apply the delegate to all columns:

class BlobDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(BlobDelegate, self).initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignCenter

    def displayText(self, value, locale):
        if isinstance(value, QtCore.QByteArray):
            value = value.data().decode()
        return super(BlobDelegate, self).displayText(value, locale)
delegate = BlobDelegate(w)
w.setItemDelegate(delegate)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • If I understand you correctly I should use your modifications in the ```BlobDelegate``` class and to add to add the same definition in my code which will handle the text alignment. Then you are calling in on the QTableView (w in my case) to apply it for all columns right ? I don`t need to do something else for each separate column right ? I am asking because now when I do these changes nothing happens. – Veleslav Panov Aug 17 '20 at 14:59
  • @VeleslavPanov Yes, you are correct, if it doesn't work then the error is elsewhere, you can share "stats.db" to complete my test. – eyllanesc Aug 17 '20 at 15:42
  • Here is the database [link](https://drive.google.com/file/d/1a5LtNoxsoZJYEIg2xMxlknVWICUCp4ix/view?usp=sharing) see if you can do something – Veleslav Panov Aug 18 '20 at 11:17
  • @VeleslavPanov I get the following: https://i.imgur.com/L9ochjC.png Could you show an image of what you get? – eyllanesc Aug 18 '20 at 13:54
  • I decided to remove the whole code and to copy paste it again, and now it worked. Probably there was a typo somewhere and pycharm didn`t detect it. The good is that it works. Thanks a lot ! – Veleslav Panov Aug 18 '20 at 14:18
  • The answer by @eyllanesc is correct, it solved the problem, and thus is useful. However, the last few words--"_have to_ ... _apply the delegate to all columns_"--are not necessary. It is perfectly valid for the programmer to choose which columns the custom `BlobDelegate` can be applied to. E.g., the line `w.setItemDelegateForColumn(4, delegate)` that @VeleslavPanov coded in the original question is fine if that's the only column (4) you want centered. – GlobalSoftwareSociety Oct 05 '21 at 06:20