如何知道单击QTreeView项目装饰

时间:2015-07-15 18:28:47

标签: c++ qt qtreeview

我试图知道用户何时选择项目的装饰,因为我试图实现单击展开/折叠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语句中有条件。

我如何知道装饰是否被选中而不是项目本身或如何阻止装饰动作?

1 个答案:

答案 0 :(得分:1)

试试这个:

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 );
    }
}
相关问题