zoukankan      html  css  js  c++  java
  • QT中实现上下文菜单(右键菜单)

    在许多的应用程序中,当我们右击时会弹出一个菜单,这个菜单就叫做“上下文菜单”,英文名称为“Context Menu”.在QT中有两种方式可以实现这种上下文菜单,一一列举如下:

       一.重载contextMenuEvent()函数,一个简单的示例如下:

    void MainWindow::contextMenuEvent(QContextMenuEvent *event)

    {

      filemenu->addAction(newAction);

      filemenu->addAction(editAction);

      filemenu->addAction(delAction);

      filemenu->exec(QCursor::pos());         //位于鼠标点击处

      //filemenu->exec(this->mapToGlobal(QPoint(0,0)));

    //位于父组件的(0,0)坐标处

      //event->accept();//有时候需要加上这句,因为许多情况下默认为ignore事件

    }

      二.在类的构造函数中进行相关设置,如我们可以定义如下函数,再在构造函数中调用它

    void MainWindow::createContextMenu()

    {

      addAction(newAction);

      addAction(editAction);

      addAction(delAction);

      setContextMenuPolicy(Qt::ActionsContextMenu);

    }

     

       其中

    Qt::ActionsContextMenu是位于Qt命名空间的一个枚举类型,它的定义为:

      enum Qt::ContextMenuPolicy

      This enum type defines the various policies a widget can have with respect to showing a context menu.

    Qt::NoContextMenu        0     the widget does not feature a context menu, context menu handling is deferred to the widget's parent.

    Qt::DefaultContextMenu   1     the widget's QWidget::contextMenuEvent() handler is  called.

    Qt::ActionsContextMenu   2     the widget displays its QWidget::actions() as context menu.

    Qt::CustomContextMenu    3     the widget emits the QWidget::customContextMenuRequested() signal.

    Qt::PreventContextMenu   4     the widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget's parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through mousePressEvent(), and mouseReleaseEvent().

       今天又在书上看到这么一段话,刚好可以用在这里,首先来看一下这段话:

       Creating modal dialogs and context menus in QWidget::contextMenuEvent() reimplementations on the stack is a common programming pattern since we usually don't need the dialog or menu after we have used it,and it will automatically be destroyed at the end of the enclosing scope.

      根据这段话所说,我们要对程序进行修改的话,只需要把QMenu与QAction的实例化放在相应的函数里面,可以直接用一个变量,也可以用new,不过用new的时候要记得在函数结尾处要调用delete。这个比较简单,就不在这里列出相应的代码了。

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ryanzz/archive/2010/03/16/5384548.aspx

  • 相关阅读:
    java环境的配置
    java基本语法
    QTP的那些事QTP回放iFrame控件时间非常慢的问题分析
    QTP的那些事有关xml的操作函数
    QTP的那些事xpath的使用(转)
    QTP的那些事有关web的自动化测试框架saffron的使用
    selenium的那些事命令行启动selenium并运行测试(转)
    QTP的那些事XPath的重要使用
    QTP的那些事有关report manager的使用
    测试环境服务器windows server 2003资源下载
  • 原文地址:https://www.cnblogs.com/csstudy/p/3674627.html
Copyright © 2011-2022 走看看