由于上下文菜单添加的action后右击鼠标也会触发QAction的triggered信号,所以添加了事件过滤,并且安装给QMenu的实列化。(代码粘贴复制到vs即可运行)
file.h--------------------------------------------------------------------------------------------------
#include <QtWidgets/QMainWindow>
#include "ui_sortmethod.h"
#include <QTableView>
#include <QStandardItemModel>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QMouseEvent>
class TableViewWithContextMenu : public QTableView {
Q_OBJECT
public:
TableViewWithContextMenu(QWidget* parent = nullptr) : QTableView(parent) {
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QTableView::customContextMenuRequested, this, &TableViewWithContextMenu::showContextMenu);
}
protected:
bool eventFilter(QObject* obj, QEvent* event) override {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
// 过滤右键点击事件
if (mouseEvent->button() == Qt::RightButton) {
return true; // 拦截事件,不传递给其他处理程序
}
}
else if (event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
// 过滤右键双击事件
if (mouseEvent->button() == Qt::RightButton) {
return true; // 拦截事件,不传递给其他处理程序
}
}
// 对于其他事件,保持默认处理
return QObject::eventFilter(obj, event);
}
private slots:
void showContextMenu(const QPoint& pos) {
QModelIndex index = indexAt(pos);
if (index.isValid()) {
QMenu contextMenu;
QAction* action1 = new QAction("Option 1", this);
QAction* action2 = new QAction("Option 2", this);
contextMenu.installEventFilter(this);
connect(action1, &QAction::triggered, this, [=]() {
// 仅在左键点击时处理
QMessageBox::information(this, "Option 1", "You selected Option 1");
});
connect(action2, &QAction::triggered, this, [=]() {
// 仅在左键点击时处理
QMessageBox::information(this, "Option 2", "You selected Option 2");
});
contextMenu.addAction(action1);
contextMenu.addAction(action2);
contextMenu.exec(mapToGlobal(pos));
}
}
};
main.h--------------------------------------------------------------------------------------------------
#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
// 创建模型并填充数据
QStandardItemModel model(5, 3);
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 3; ++col) {
QStandardItem* item = new QStandardItem(QString("Item %1-%2").arg(row + 1).arg(col + 1));
model.setItem(row, col, item);
}
}
// 创建带有上下文菜单的 QTableView
TableViewWithContextMenu tableView;
tableView.setModel(&model);
tableView.show();
return app.exec();
}