Nominate our 2022 Qt Champions!

QSqlQueryModel With QTableView

  • Dear All

    I have implemented a QTableView with QSqlQueryModel and I am able to display the data , but I am unable to align the text to center.The text is align to left by default.
    Some of the post says that the QSqlQueryModel has to be subclassed Is there any option without subclassing the text can be aligned in the tableview if not can any one provide a small subclassed example to start with .

    Thanks & Regards

  • Hi,
    You should reimplement the data() method and return the alignment you want, like this:

    QVariant YourModel::data(const QModelIndex &item, int role) const
        return QVariant();
    if (item.column() == /*The column number where your text appears*/) {
        if (role == Qt::QtTextAlignmentRole)
             return Qt::AlignCenter;
    return QSqlQueryModel::data(item,role);

    Otherwise I think you need to provide a custom delegate and manipulate text in there, but I don't think you'll save more time or trouble.

  • @Shiv
    Here is a sub classing using QAbstractTableModel and override data() like this .

  • Hi @panosk ,@Ratzz
    Thanks for your kind reply.I was trying to subclass the QSqlQueryModel to reimplement the data function but I am bit confused with the constructor given in the class document ,by default the active database will be connected or we have to pass a database to get connected.If possible can you post a simple class example with only its constructor and initialization.


  • Hi

    I got the example from

    Thank you

Log in to reply