Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to get DisplayRole?



  • I have a delegate for my TreeView with a paint method like the following, but the problem is that when the mouse hovers over a row, index_data is always empty showing "".

    void MyTreeViewDelegate::paint(QPainter *painter,
    const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QModelIndex parent = index.parent();
        QModelIndex child = index.sibling(parent.row(), parent.column());
    
        QString index_data = index.data(Qt::DisplayRole).toString();
    
        if (option.state & QStyle::State_MouseOver) {
            std::cout << "got a mouse over" << std::endl;                         
    
        qDebug() << "index_data: " << index_data;
        }           
        // ...
    }
    

    Any thoughts where I'm going wrong?


  • Lifetime Qt Champion

    Hi
    the same code works fine with a QStandardItemModel
    alt text

    so my guess is that you use a custom model and there is something with the index or it
    uses EditRole and not Display role.



  • I do use a custom model. I'm hoping the following helps in some way.

    QVariant MyTreeModel::data(const QModelIndex &index, int role) const
    {
        QModelIndex parent = index.parent();
        QModelIndex child = index.sibling(parent.row(), parent.column());
    
        if (!index.isValid())
            return QVariant();
    
        MyTreeItem *item = static_cast<MyTreeItem *>
            (index.internalPointer());
    
        if (role == Qt::CheckStateRole) {
            if (parent.row() == 0 && index.column() == 0)
                return static_cast<int>(item->getChecked() ? Qt::Checked :
                Qt::Unchecked);
        }
    
        if (role != Qt::DisplayRole)
            return QVariant();
    
        return item->data(index.column());
    }

  • Lifetime Qt Champion

    Hi
    Try to qDebug() << index in delegate and
    then call
    MyTreeModel::data with same index and see if it returns anything valid.

    also did you reuse the model from here ?
    https://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html


Log in to reply