Qt自定义上下文菜单

时间:2012-05-22 07:40:10

标签: qt qt-creator qtreeview qt-contextmenu

创建一个由树视图和webview组成的Qt应用程序。当单击树视图中的项时,它应该加载相应的URL。 工作正常。当我右键单击该项目时,将出现一个自定义上下文菜单,它将在新的webview中打开它。 这也有效。但我的问题是,当我右键单击树视图项目时,我的上下文菜单出现,如果在弹出菜单外单击它,则该项目的URL将被加载。怎么解决这个..帮帮我的朋友..

这是我的编码:

    QStandardItem *rootItem         =  new QStandardItem("Google");
    QStandardItem *stackItem        =  new QStandardItem("Stack Overflow");
    QStandardItem *yahooItem        =  new QStandardItem("Yahoo");

    rootItem->appendRow(stackItem);
    standardModel->appendRow(rootItem);
    standardModel->appendRow(yahooItem);

***// private slot for loading the url if a treeview item is clicked:***

void MainWindow::treeViewClicked(const QModelIndex &index)
{
    str = index.data().toString();

    if(!(str.isEmpty()) && str=="Google")
    {
        url  = "http://www.google.com";
    }

    else if (!(str.isEmpty()) && str == "stack Overflow")
    {
        url = "http://www.stackoverflow.com";
    }

    else if (!(str.isEmpty()) && str == "Yahoo")
    {
        url = "http://www.yahoo.com";
    }

    WebView *wv = dynamic_cast<WebView *>(ui->tabWidget->currentWidget());
    wv->load(QUrl(url));
    ui->tabWidget->setTabText(ui->tabWidget->currentIndex(),str);

    treeView->setModel(standardModel);

**//Creating custom context menu for QtreeView:**

void MainWindow::showContextMenu(const QPoint& point)
{
    QList<QAction *> actions;
    if(treeView->indexAt(point).isValid())
    {
        actions.append(m_treeViewAction);
    }

    else if(actions.count() > 0)
    {
        QMenu::exec(actions, MainWindow::treeView->mapToGlobal(point));
        QModelIndex index = treeView->indexAt(point);
        QStandardItem *item = standardModel->itemFromIndex(index);
        treeView->setCurrentIndex(index);
        treeViewClicked(index);
    }

}

1 个答案:

答案 0 :(得分:3)

据我所知,您描述的情况是视图中的上下文菜单的标准:当您右键单击时,该项目也会被选中。

如果您想要其他行为,则必须实施mousePressEvent并实施您想要实现的行为。

这是一个提示:

void MyTreeView::mousePressEvent ( QMouseEvent * event )
{
     if (event->button() == Qt::LeftButton) {
       // set the current item based on event->pos() / deselect if no item
     }
     else if (event->button() == Qt::RightButton) {
       // show context menu for the item / different context menu if no item
     }
}

是的,您必须派生QTreeView类并制作自己的类。

我很久以前就已经这么做了,我记得这是一个起点。我现在不记得是否必须重新实现所有四个基本鼠标事件:按下,释放,移动和双击,因为它们是内部相关的。