c++ - 如何知道QTreeView项装饰被点击

标签 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条件。如果不是,则一切正常。

不知道是非要阻塞装饰 Action 还是在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 );
    }
}

关于c++ - 如何知道QTreeView项装饰被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31438299/

相关文章:

C++:我需要释放函数内部的指针吗?

c++ - 如何从函数返回多维 Mat 数组

c++ - 为什么没有声明 putenv()?

c++ - Qt Signal Slots 类作用域类型

c++ - QThread的复杂使用——

c++ - 在 QTreeView 中插入和删除行

c++ - 以十六进制表示位串的最佳实践(Arduino)

c++ - 如何根据圆上中点和其他点之间的角度计算圆上的点

c++ - 为什么 QTreeView 不显示数据?

qt:我想禁用为 QTreeView 自动设置的键绑定(bind)