qtreeview item text too long

  • in my QTreeView i have an item whose text is long so currently my item takes up height of three normal rows.

    i've tried setting setWordWrap(false), setUniformRowHeights(true) and setTextElideMode(Qt::ElideRight) to the tree view but none worked.

    when i widen the column, the text appears in three rows. what i need is the text to appear in one row, and i wanna have the text elided from right. how can i do that?

  • Lifetime Qt Champion


    Can you give a minimal compilable example that shows that behaviour ?
    What version of Qt are you using ?
    On what platform ?

  • @SGaist
    right now i'm on mobile so i'm afraid i can't provide an example. will do when i get to my computer.
    i'm using v5.11.1, on linux.

  • @SGaist
    sorry but i cannot write an example that shows the behavior.
    but in my actual code i have a tree view two modes.
    when i have this structure:

    "small text"
    |__"long text"

    the row heights are okay. but when i have

    "long text"
    |__"short text"

    both rows have the height of three normal rows (i've set setUniformRowHeights(true), when i remove it, only first row is tall).

  • Qt Champions 2018

    Summoning @Christian-Ehrlicher as I think this one is a bug he sqashed

  • Qt Champions 2018

    @VRonin: According from the description it could be but we can't check... so @user4592357 either post some code to reproduce the problem or test with 5.12.3

  • i finally understood what the problem is. my item had newlines in it.
    but if i remove the newlines in my items then i will have two problems:

    1. for every item i'll have to do it
    2. i'm using these node texts in sql queries. so when i removed the newlines, the text didn't match the text in the database.
      what can i do here?

  • Qt Champions 2018

    class NoNewLinesDelegate : public QStyledItemDelegate {
        QString displayText(const QVariant &value, const QLocale &locale) const Q_DECL_OVERRIDE
            QString baseText = QStyledItemDelegate::displayText(value, locale);
            return baseText.replace(m_newLineRegExp,QStringLiteral(" "));
        explicit NoNewLinesDelegate(QObject* parent = Q_NULLPTR)
            : QStyledItemDelegate(parent)
            , m_newLineRegExp(QStringLiteral("[\r\n]+"))
        const QRegularExpression m_newLineRegExp;

    Now you just need to call treeView->setItemDelegate(new NoNewLinesDelegate(treeView));

  • @VRonin
    thanks but actually my bigger concern was the problem #2

  • Qt Champions 2018

    Yes, the point of my solution is that you don't have to change the data at all, you just change how the data is displayed.
    Leave the newlines in the model and implement the solution above

  • @VRonin
    yes i just realized it's the displayText() method. thank you. and also can you please format the code so it's better readable? :)


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