如何知道QTreeView项装饰被点击

How to know the QTreeView item decoration is clicked

我想知道用户何时选择项目的装饰,因为我试图实现单击 expand/collapse QTreeview,而装饰现在什么都不做。它不会展开或折叠项目,就像我点击它正常工作的项目一样。

void MyTreeView::mousePressEvent(QMouseEvent *event)
{
    QTreeView::mousePressEvent(event);

    if (event->button() == Qt::LeftButton)
    {
        QModelIndex index = indexAt(event->pos());

        isExpanded(index) ? collapse(index) : expand(index);
    }
}

问题是选择装饰的时候,进入了if条件。如果不是,则一切正常。

不知道是不是要屏蔽装饰动作,还是if语句里有条件

我怎么知道选择了装饰而不是项目本身,或者如何阻止装饰操作?

试试这个:

void MyTreeView::mousePressEvent( QMouseEvent* aEvent )
{
    QModelIndex index = indexAt( aEvent->pos() );

    if ( index.isValid() )
    {
        const bool wasExpanded = isExpanded( index );

        QTreeView::mousePressEvent( aEvent );

        if ( aEvent->button() == Qt::LeftButton )
        {
            const bool expanded = isExpanded( index );

            // QTreeView did not change the item's state ... but you want.
            if ( wasExpanded == expanded )
            {
                expanded ? collapse( index ) : expand( index );
            }
        }
    }
    else
    {
        QTreeView::mousePressEvent( aEvent );
    }
}