Search code examples
c++qtqtreewidget

How to align the text in qtreewidget column in this manner : "...qtreewidgetitemdata" instead of "qtreewidgetitemdata..."?


How to align data in column 1 of qtreewidget in this manner:

|Column1 |Column2|
|+...abcd|efgh   |
|+...ijkl|mnop   |

instead of

|Column1 |Column2|
|+xyab...|efgh   |
|+pqij...|mnop   |

Solution

  • You have to establish the elide mode with a delegate:

    #include <QtWidgets>
    
    class ElideLeftDelegate: public QStyledItemDelegate
    {
    public:
        using QStyledItemDelegate::QStyledItemDelegate;
    protected:
        void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const{
            QStyledItemDelegate::initStyleOption(option, index);
            option->textElideMode = Qt::ElideLeft;
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QTreeWidget w;
        w.setItemDelegateForColumn(0, new ElideLeftDelegate{&w});
        w.setColumnCount(2);
        new QTreeWidgetItem(&w, {"abcdefghijklmnopqrdstuvwxyz", "AVCDEFGHIJKLMNOPQRSTUVWXYZ"});
        new QTreeWidgetItem(&w, {"AVCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrdstuvwxyz"});
        w.show();
        return a.exec();
    }
    

    enter image description here