您的位置:首页 > 编程语言 > Qt开发

VTK:基于Qt的VTK右击菜单实现

2016-05-07 13:38 1011 查看
   前面试过在Qt中实现右击菜单Qt右击菜单  现在尝试在嵌套在Qt中的VTK窗口实现右击菜单 原有方式不能成功。原因也很简单:在VTK窗口发送的是VTKEvent 所以Qt中的

contextMenuEvent(QContextMenuEvent *event) 不会处理该事件。所以要另谋出路 翻阅VTK文档发现了一个实现右击菜单的实例 贴出来与大家分享:

void GUI4::popup(vtkObject * obj, unsigned long,
void * client_data, void *,
vtkCommand * command)
{
// A note about context menus in Qt and the QVTKWidget
// You may find it easy to just do context menus on right button up,
// due to the event proxy mechanism in place.

// That usually works, except in some cases.
// One case is where you capture context menu events that
// child windows don't process. You could end up with a second
// context menu after the first one.

// See QVTKWidget::ContextMenuEvent enum which was added after the
// writing of this example.

// get interactor
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::SafeDownCast(obj);
// consume event so the interactor style doesn't get it
command->AbortFlagOn();
// get popup menu
QMenu* popupMenu = static_cast<QMenu*>(client_data);
// get event location
int* sz = iren->GetSize();
int* position = iren->GetEventPosition();
// remember to flip y
QPoint pt = QPoint(position[0], sz[1]-position[1]);
// map to global
QPoint global_pt = popupMenu->parentWidget()->mapToGlobal(pt);
// show popup menu at global point
popupMenu->popup(global_pt);
}这是一个槽函数。使用vtkEventQtSlotConnect函数与VTK事件连接。函数介绍在之前的VTK交互有介绍。重点是使用客户数据来传递一个菜单。

看了这个实例感觉VTK对Qt兼容性相当好 提供了这么强大的函数来实现Qt和VTK的连接。 之前看了很多人关于Qt右击菜单的实现 发现需要手动delete 否则会内存泄漏。想想看 如果不手动delete 每次右击都会new一个菜单出来。

//实现右击菜单
void fileView::contextMenuEvent(QContextMenuEvent *event)
{
QMenu* popMenu = new QMenu(this);
QModelIndex currIndex=this->tree->indexAt(tree->viewport()->mapFromGlobal(event->globalPos()));
int i=currIndex.row();
// qDebug()<<"right:"<<i;
if(i!=-1)
{
QAction *Rename=new QAction(QObject::tr("Rename"),popMenu);//父对象指向Menu
popMenu->addAction(Rename);
connect(Rename,SIGNAL(triggered(bool)),this,SLOT(slotRename()));
}
popMenu->exec( QCursor::pos() );
popMenu->deleteLater(); //发出删除事件到主循环队列
}
今天看了这个实例 突然意识到 右击菜单作为一个程序的常用组件,每次用时new一个然后再delete,个人感觉过于复杂了 完全可以把其作为全局变量在构造函数中实现。这样在弹出菜单函数中直接调用该菜单实例就好 这样也不存在反复new和delete.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  VTK qt