tableView->setContextMenu(menu);没有这个方法
时间: 2024-04-08 22:34:50 浏览: 59
非常抱歉,我犯了一个错误。确实没有`setContextMenu()`方法来直接设置上下文菜单。在Qt中,可以通过重写`contextMenuEvent()`方法来自定义上下文菜单。以下是修改后的代码:
```cpp
QTableView* tableView = new QTableView(this);
QMenu* menu = new QMenu(tableView);
QAction* addAction = new QAction("添加数据", this);
QAction* deleteAction = new QAction("删除行", this);
menu->addAction(addAction);
menu->addAction(deleteAction);
tableView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(tableView, &QTableView::customContextMenuRequested, this, [=](const QPoint& pos) {
menu->exec(tableView->viewport()->mapToGlobal(pos));
});
connect(addAction, &QAction::triggered, this, [=]() {
QAbstractItemModel* model = tableView->model();
model->insertRow(model->rowCount());
});
connect(deleteAction, &QAction::triggered, this, [=]() {
QItemSelectionModel* selectionModel = tableView->selectionModel();
QModelIndexList selectedRows = selectionModel->selectedRows();
if (!selectedRows.isEmpty()) {
QAbstractItemModel* model = tableView->model();
for (const QModelIndex& index : selectedRows) {
model->removeRow(index.row());
}
}
});
```
现在,您可以在QTableView上实现右键菜单栏,并进行插入数据和删除选中行的操作。再次对我之前的错误表示歉意,并感谢您的指正。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)