在 QTreeWidget 中调用上下文菜单 [英] Invoking context menu in QTreeWidget

查看:71
本文介绍了在 QTreeWidget 中调用上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击 QTreeWidgetItem 中的对象时,我想弹出一个菜单.我想从 QWidget 捕获信号 contextMenuRequested 然后使用 itemAt 从视图中检索索引.但这似乎不是很漂亮.有没有更简单的方法可以在视图内的项目上调用菜单?

I would like to popup a menu, when user clicks on an object in QTreeWidgetItem. I though about catching signal contextMenuRequested from QWidget and then retrieving index from the view using itemAt. But this doesn't seem very pretty. Is there any easier way to be able to call a menu on an item inside a view?

推荐答案

编写自己的自定义 ItemDelegate 并在 QAbstractItemDelegate::editorEvent 中处理点击事件.您可以从 QModelIndex 检索单元格中的数据.在 C++ 中,它看起来像这样:

Write your own custom ItemDelegate and handle the click event in QAbstractItemDelegate::editorEvent. You can retreive the data in the cell from the QModelIndex. In C++ it would look like this:

class ItemDelegate: public QItemDelegate
{
public:
    ItemDelegate(ContextMenuHandler *const contextMenu, QObject *const parent )
        : QItemDelegate(parent)
        , m_contexMenu(contextMenu) 
    {
    }

    bool editorEvent( 
            QEvent * event, 
            QAbstractItemModel * model, 
            const QStyleOptionViewItem & option, 
            const QModelIndex & index )
    {
        if((event->type()==QEvent::MouseButtonPress) && index.isValid())
        {
            QMouseEvent *const mouseEvent = qobject_cast<QMouseEvent>(event);
            if(mouseEvent && (mouseEvent->button()==Qt::RightButton))
            {
                return m_contexMenu->showContextMenu(mouseEvent->pos(), index);
            }
        }
    }
    ContextMenuHandler *const m_contextMenu;
};

treeWidget->setItemDelegate(new ItemDelegate(contextMenuHandler,treeWidget));

这篇关于在 QTreeWidget 中调用上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆