c++qtqtreewidget

How to set QTreeWidget row height


I want to set the height of all QTreeWidgetItems in a QTreeWidget to a specified height. I couldn't see anything in Qt Designer or the QTreeWidget class documentation.


Solution

  • In order to modify the tree item row,

    create your own customized QItemDelegate and override the sizeHint() function.

    For example:

    class ItemDelegate : public QItemDelegate
    {
    private:
        int m_iHeight;
    public:
        ItemDelegate(QObject *poParent = Q_NULLPTR, int iHeight = -1) :
            QItemDelegate(poParent), m_iHeight(iHeight)
        {
        }
    
        void SetHeight(int iHeight)
        {
            m_iHeight = iHeight;
        }
    
        // Use this for setting tree item height.
        QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
        {
            QSize oSize = QItemDelegate::sizeHint(option, index);
    
            if (m_iHeight != -1)
            {
                // Set tree item height.
                oSize.setHeight(m_uHeight);
            }
    
            return oSize;
        }
    };
    

    Then in your class, set the custome delegate item to the tree,

    and change the row height as you like:

    class YourClass
    {
    private:
        QTreeWidget *m_poTreeWidget;
        ItemDelegate m_oItemDelegate;
    public:
        void InitTree()
        {
            // do stuff
            m_oItemDelegate.SetHeight(30); // set row height
            m_poTreeWidget->setItemDelegate(&m_oItemDelegate);
            // ...
        }
    };