Qt工作笔记-自定义菜单(右键菜单)

Qt工作笔记-自定义菜单(右键菜单)_第1张图片

 

所以,只要重写createWIdget()这个函数就阔以了!

Qt工作笔记-自定义菜单(右键菜单)_第2张图片

把写好的界面放到这个parent里面不就阔以了!

写好的界面如下:

Qt工作笔记-自定义菜单(右键菜单)_第3张图片

 

运行截图如下:

 

 

源码如下:

mypopwidget.h

#ifndef MYPOPWIDGET_H
#define MYPOPWIDGET_H

#include 

namespace Ui {
class MyPopWidget;
}

class MyPopWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MyPopWidget(QWidget *parent = 0);
    ~MyPopWidget();

private:
    Ui::MyPopWidget *ui;
};

#endif // MYPOPWIDGET_H

mywidgetaction.h

#ifndef MYWIDGETACTION_H
#define MYWIDGETACTION_H

#include 
#include 


class MyWidgetAction : public QWidgetAction
{
    Q_OBJECT
public:
    explicit MyWidgetAction(QWidget *parent = 0);

protected:
    QWidget *createWidget(QWidget *parent);
};

#endif // MYWIDGETACTION_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
class QMenu;

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    void onContextMenu(const QPoint &pt);

private:
    Ui::Widget *ui;
    QMenu *m_menu;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

mypopwidget.cpp

#include "mypopwidget.h"
#include "ui_mypopwidget.h"

MyPopWidget::MyPopWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyPopWidget)
{
    ui->setupUi(this);
}

MyPopWidget::~MyPopWidget()
{
    delete ui;
}

mywidgetaction.cpp

#include "mywidgetaction.h"
#include "mypopwidget.h"

MyWidgetAction::MyWidgetAction(QWidget *parent)
    : QWidgetAction(parent)
{

}

QWidget *MyWidgetAction::createWidget(QWidget *parent)
{
    MyPopWidget *myPopWidget=new MyPopWidget(parent);
    return myPopWidget;
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 
#include "mywidgetaction.h"
#include 

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->listView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(onContextMenu(QPoint)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onContextMenu(const QPoint &pt)
{
    m_menu=new QMenu(this);
    MyWidgetAction *widgetAction=new MyWidgetAction(m_menu);
    m_menu->addAction("传统的-第一个右键");
    m_menu->addAction(widgetAction);
    m_menu->exec(ui->listView->mapToGlobal(pt));
}

 

你可能感兴趣的:(C/C++,Qt,工作笔记)