1

我正在创建一个由树视图和 web 视图组成的 Qt 应用程序。当单击树视图中的项目时,它应该加载相应的 url。它工作正常。当我右键单击该项目时,将出现一个自定义上下文菜单,它将在新的 web 视图中打开它。这也行得通。但是我的问题是,当我右键单击树视图项目时,我的上下文菜单会出现,如果在弹出菜单之外单击它,则会加载该项目的 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);
    }

}
4

1 回答 1

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 类并自己创建一个。

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

于 2012-05-22T13:51:42.530 回答