[英]How to customise or disable right click menu on offline plotly plot?
我正在以與此代碼類似的方式創建離線 plotly plot:
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_()
使用鼠標左鍵單擊我可以訪問導航(如縮放平移),但右鍵單擊目前對我來說絕對沒用,所以我想將我自己的操作放在右鍵菜單中,或者如果不可能的話至少禁用它。 plotly 有沒有辦法做到這一點?
您必須覆蓋 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.