Qt World Summit: Submit your Presentation

How to automatically change row height in QTableView on resize

  • Hi,
    I have a QTableModel and a QTableView with a couple of columns.
    I have the second column set to expand, the rest has fixed width.
    When I expand the widget, the second column expands as well.
    I have word wrapping and it also works.
    But no mater how many lines the text occupy, the row height stays the same as on start of the program.
    Does any one know how to implement auto-resize of rows height in a TableView?

    I have set my QTableView like this:

        itemDelegate = new MyItemDelegate(this);
                tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);

    I do not have a custom delegate implemented in this moment, but in a more advanced aplication I have tried SizeHint in a custom delegate, as shown below, but it does not work:

    QSize MyItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
        if(index.column() == 2){
        QStyleOptionViewItem options = option;
        initStyleOption(&options, index);
        QTextDocument textDoc;  
        QString contactName = index.data(Qt::DisplayRole).toString();
        QString contactPhone = index.data(Qt::UserRole).toString();
        QString contactInfo = index.data(Qt::UserRole+1).toString();
        QTextCursor textCursor(&textDoc);
        QImage stanPoint = index.data(Qt::UserRole+2).value<QImage>();
        bool wczytajfote = !stanPoint.isNull();
        textCursor.movePosition(QTextCursor::EndOfLine, QTextCursor::MoveAnchor);
        textCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
        return QSize(textDoc.idealWidth(), textDoc.size().height());
        } else return QSize(30,30);

    in the mentioned app the QStyleOptionViewItem option does not pass any height.

  • Lifetime Qt Champion

    Maybe something like
    Not sure its the effect you are after.

  • Thank You for the suggestion, but unfortunately I have already tried it.
    It just makes the rows have the same height and stretch, to fit the whole QTableView height.

  • Lifetime Qt Champion

    Ok. it was worth a shot :)
    As far as I know there is no automatically way to adjust word wrap according
    to text height.

Log in to reply