树形控件QTreeView添加右键菜单

时间:2022-09-02 20:25:18

第一步

//设置treeView可以使用右键菜单

ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);


第二步,在槽函数添加右键菜单

voidMainWindow::on_treeView_customContextMenuRequested(constQPoint&pos)

{

    qDebug()<<"on_treeView_customContextMenuRequested";

    QModelIndexindex=ui->treeView->currentIndex();

    QStringfileName=ui->treeView->model()->data(index).toString();

    QMenu*menu=newQMenu;

    menu->addAction(QString(tr("%1-Import").arg(fileName)),this,SLOT(slotTest()));

    menu->addAction(QString(tr("%1-Export").arg(fileName)),this,SLOT(slotTest()));

    menu->exec(QCursor::pos());

}