如何在离线绘图上自定义或禁用右键菜单?

Posted

技术标签:

【中文标题】如何在离线绘图上自定义或禁用右键菜单?【英文标题】:How to customise or disable right click menu on offline plotly plot? 【发布时间】:2021-11-23 18:51:14 【问题描述】:

我正在以与此代码类似的方式创建一个离线情节图:

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow
import plotly.graph_objects as go
import plotly

import numpy as np


class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        # some example data
        x = np.arange(1000)
        y = x**2

        # create the plotly figure
        fig = go.Figure(go.Scatter(x=x, y=y))

        # we create html code of the figure
        html = '<html><body>'
        html += plotly.offline.plot(fig, output_type='div', include_plotlyjs='cdn')
        html += '</body></html>'

        # we create an instance of QWebEngineView and set the html code
        plot_widget = QWebEngineView()
        plot_widget.setHtml(html)

        # set the QWebEngineView instance as main widget
        self.setCentralWidget(plot_widget)


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

通过鼠标左键单击我可以访问导航(如缩放平移),但右键单击目前对我来说绝对没用,所以我想将我自己的操作放在右键菜单中,或者如果它是至少不可能禁用它。有没有办法在情节中做到这一点?

【问题讨论】:

【参考方案1】:

您必须重写 contextMenuEvent 方法并添加所需的 QActions 和 QMenus。

from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView

import plotly.graph_objects as go
import plotly

import numpy as np


class WebEngineView(QWebEngineView):
    def contextMenuEvent(self, event):
        menu = self.page().createStandardContextMenu()
        menu.addSeparator()
        custom_action = menu.addAction("Custom Action")
        custom_action.triggered.connect(self.handle_custom_action)
        menu.exec_(event.globalPos())

    def handle_custom_action(self):
        print("custom_action")


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        x = np.arange(1000)
        y = x ** 2

        fig = go.Figure(go.Scatter(x=x, y=y))

        html = "".join(
            [
                "<html><body>",
                plotly.offline.plot(fig, output_type="div", include_plotlyjs="cdn"),
                "</body></html>",
            ]
        )

        plot_widget = WebEngineView()
        plot_widget.setHtml(html)

        self.setCentralWidget(plot_widget)


if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

如果要禁用上下文菜单,则必须将 Qt.NoContextMenu 设置为 contextMenuPolicy:

plot_widget.setContextMenuPolicy(Qt.NoContextMenu)

【讨论】:

谢谢!它工作得几乎完美,有没有办法也可以从菜单中删除默认操作? @Flash333 只更改为menu = QMenu()

以上是关于如何在离线绘图上自定义或禁用右键菜单?的主要内容,如果未能解决你的问题,请参考以下文章

如何禁用右键单击事件或如何隐藏 Autodesk Forge 查看器上的上下文菜单

如何禁用html中的右键菜单? [复制]

VBA:如何从右键单击上下文菜单中禁用某些选项

C# winform如果禁用右键菜单和其它功能键盘

怎样在注冊表禁用或打开windows系统右键菜单

禁用文件夹背景右键菜单