Set QTableWidgetItem maximum displayed text length (truncate and add ellipsis if longer)

  • Hi,

    I have a QTableWidget populated by QTableWidgetItems. Each row contains a description of the item in that row which can be quite long. I would like to only have for example max 15 characters of the description shown in the table. If the description is longer it will show the 15 characters and an ellipsis. The full description is shown in the tooltip of that row when the user hovers over it.

    I tried using QLineEdit as the cell widget and using QLineEdit::setMaxLength(15) but this just truncates the text and does not show the ellipse which does not inform the user that some of the text is not displayed.

    Is there a way to do it?

  • Moderators


    install a custom QStyledItemDelegate on your table.

    void MyItemDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
         QStyledItemDelegate::initStyleOption(option, index);
         option->textElideMode = Qt::ElideRight;

    or (also untested and a bit dirty):

    void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
        QStyleOptionViewItem & opt = const_cast<QStyleOptionViewItem &>(option);
        const int width = opt.widget ? opt.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget).width() : opt.rect.width()-4;
        opt.text = QFontMetrics(opt.font).elidedText(opt.text, Qt::ElideRight, width, 0);
        QStyledItemDelegate::paint(painter, opt, index);

  • Thanks I ended up doing the simplest thing:

    QString descriptionText = QFontMetrics(table->font()).elidedText(m_description, Qt::ElideRight, uiSettings::descriptionTextWidth, 0);
    QTableWidgetItem *descriptionItem = new QTableWidgetItem(descriptionText);
    table->setItem(r, 0, descriptionItem);

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.