问题代码:
void MainWindow::onCustomContextMenuRequested(const QPoint &pos)
{QTreeWidgetItem *item = ui->treeWidget->itemAt(pos);if (item){QMenu menu(ui->treeWidget);TreeNodeType nodeType = (TreeNodeType)item->data(0, Qt::UserRole + 1).toInt();if (nodeType == NODE_CONNECTION){QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);QAction actionModify("编辑连接", ui->treeWidget);connect(&actionModify, &QAction::triggered, this, &MainWindow::onModifyConnectionTriggered);menu.addAction(&actionModify);}else if (nodeType == NODE_DATABASE){qDebug() << "NODE_DATABASE";QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);}else if (nodeType == NODE_TABLE){qDebug() << "NODE_TABLE";QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);}qDebug() << "why?";menu.exec(QCursor::pos());}
}
想着先声明QMenu然后根据右键的不同类型节点弹出不一样的菜单,结果这样一直无法显示菜单。调试发现代码是按照预想的逻辑走的,后面想起一种可能:QAction在if里面定义,离开if的时候,QAction对象已经被释放掉了。然后把代码改成下面这样:
void MainWindow::onCustomContextMenuRequested(const QPoint &pos)
{QTreeWidgetItem *item = ui->treeWidget->itemAt(pos);if (item){TreeNodeType nodeType = (TreeNodeType)item->data(0, Qt::UserRole + 1).toInt();if (nodeType == NODE_CONNECTION){QMenu menu(ui->treeWidget);QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);QAction actionModify("编辑连接", ui->treeWidget);connect(&actionModify, &QAction::triggered, this, &MainWindow::onModifyConnectionTriggered);menu.addAction(&actionModify);menu.exec(QCursor::pos());}else if (nodeType == NODE_DATABASE){QMenu menu(ui->treeWidget);qDebug() << "NODE_DATABASE";QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);menu.exec(QCursor::pos());}else if (nodeType == NODE_TABLE){QMenu menu(ui->treeWidget);qDebug() << "NODE_TABLE";QAction actionOpen("打开连接", ui->treeWidget);connect(&actionOpen, &QAction::triggered, this, &MainWindow::onOpenConnectionTriggered);menu.addAction(&actionOpen);menu.exec(QCursor::pos());}}
}
再次运行,果然没问题了,又学到了。