Qt工作笔记-自定义菜单(右键菜单)
程序员文章站
2022-05-30 20:55:47
...
所以,只要重写createWIdget()这个函数就阔以了!
把写好的界面放到这个parent里面不就阔以了!
写好的界面如下:
运行截图如下:
源码如下:
mypopwidget.h
#ifndef MYPOPWIDGET_H
#define MYPOPWIDGET_H
#include <QWidget>
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 <QObject>
#include <QWidgetAction>
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 <QWidget>
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 <QApplication>
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 <QMenu>
#include <QDebug>
#include <QPoint>
#include "mywidgetaction.h"
#include <QPushButton>
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));
}
下一篇: 陆逊北伐中,诸葛亮跟陆逊谁更厉害?