QT菜单栏

文章目录

  • eventFilter事件监听
  • 设置菜单属性setContextMenuPolicy()

eventFilter事件监听

bool eventFilter(QObject *object, QEvent *event) {
    if(object == this  &&  event->type() == QEvent::ContextMenu) {
        if(currentIndex().isValid()) {
            QMenu * menu = new QMenu();
            menu->addAction("添加数据");
            menu->addAction("删除数据");
            QAction * action = menu->exec(cursor().pos());    // 弹出菜单
        }
    }
    return QWidget::eventFilter(object, event);
}

设置菜单属性setContextMenuPolicy()

void initUI() {
	QTableView * table_view = new QTableView();
	table_view->setContextMenuPolicy(Qt::CustomContextMenu);   // 自定义菜单策略
	connect(table_view,   &QTableView::customContextMenuRequested, this, &TestTabel::tableViewMenu);  // 关联信号槽
}

你可能感兴趣的:(C++\QT,qt)