一、引言
如图,我们需要在一个QTreeWidget
控件中添加了自定义右键菜单。
二、思路
如何做到的呢,很简单。浅浅记录和分享一下。
继承QTreeWidget
,定义一个子类CustomTreeWidget
,在重写contextMenuEvent
事件即可。
三、代码
#include <QTreeWidget>
#include <QAction>
#include <QMenu>
#include <QContextMenuEvent>class CustomTreeWidget : public QTreeWidget
{Q_OBJECT
public:CustomTreeWidget(QWidget* parent = nullptr);
protected:void contextMenuEvent(QContextMenuEvent* event) override;
signals:
};
#include "CustomTreeWidget.h"
#include <QComboBox>
#include <QDoubleSpinBox>
#include "NoWheelUiControls.h"CustomTreeWidget::CustomTreeWidget(QWidget *parent) : QTreeWidget(parent)
{
}void CustomTreeWidget::contextMenuEvent(QContextMenuEvent *event)
{QMenu menu(this);QAction* addGroupAction = menu.addAction(QStringLiteral("添加组"));QAction* deleteGroupAction = menu.addAction(QStringLiteral("删除当前组"));QAction* addChildAction = menu.addAction(QStringLiteral("添加子项"));QAction* deleteOneAction = menu.addAction(QStringLiteral("删除当前项"));QList<QTreeWidgetItem*> items = selectedItems();if(items.isEmpty()) return;QAction* selectedItem = menu.exec(event->globalPos());if (selectedItem == addGroupAction) { // 新建组// add codes here} else if (selectedItem == deleteGroupAction) {// 删除组// add codes here}else if(selectedItem == addChildAction) { // 添加项// add codes here}else if(selectedItem == deleteOneAction) { // 删除项// add codes here}update();
}