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

}
.

有帮助吗?

解决方案

是我所知道的,您描述的情况是标准的内容菜单中的视图:右键单击时,还会选择该项目。

如果您想要另一个行为,则必须实现生成的icetagcode并实现要实现的行为。

这里是一个提示:

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类并制作一个自己的类。

我很久以前做过,我记得这是起点。我现在不记得了,如果我不得不重新实现所有四个基本鼠标事件:按,发布,移动和doubleclick,因为它们是内部相关的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top