QWidget添加右键菜单

设置右键菜单的方法:

PySide2.QtWidgets.QWidget.setContextMenuPolicy(policy)

参数:policy:ContextMenuPolicy

项目Value
Qt.NoContextMenu该部件没有快捷菜单,快捷菜单访问的请求会被转发给部件的父对象
Qt.PreventContextMenu该部件没有快捷菜单,快捷菜单访问的请求也并不会转发给部件的父对象。这确保了所有鼠标右键事件都通过QWidget.mousePressEvent()和QWidget.mouseReleaseEvent()传递给部件自身。
Qt.DefaultContextMenu部件QWidget.contextMenuEvent()方法被调用处理
Qt.ActionsContextMenu部件展示QWidget.actions()返回数据作为快捷键
Qt.CustomContextMenu部件发送QWidget.customContextMenuRequested()信号,具体响应由信号对应的槽函数处理。
class ChartWidget(QWidget):
    def __init__(self):
        super(ChartWidget, self).__init__()
        chart = self.gv_visual_data_content = MyFigureCanvas(
            xlim=(0, 2 * np.pi),
            ylim=(-1, 1))
        x = np.arange(0, 2 * np.pi, np.pi / 100)
        y = np.cos(x)
        self.gv_visual_data_content.axes.plot(x, y)
        self.gv_visual_data_content.axes.set_title('cos()')

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(chart)
        self.setLayout(self.main_layout)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.create_rightmenu)

    def create_rightmenu(self):
        menu = QMenu(self)
        save_action = QAction("另存为")
        save_action.setShortcut('Ctrl+S')
        save_action.triggered.connect(self.save_as)
        menu.addAction(save_action)

        menu.exec_(QCursor.pos())

    def save_as(self):
        self.gv_visual_data_content.fig.savefig("fig.pdf")


class MyFigureCanvas(FigureCanvas):
    '''
    通过继承FigureCanvas类,使得该类既是一个PyQt5的Qwidget,又是一个matplotlib的FigureCanvas,这是连接pyqt5与matplotlib的关键
    '''

    def __init__(self, parent=None, width=10, height=5, xlim=(0, 2500), ylim=(-2, 2), dpi=100):
        # 创建一个Figure
        self.fig = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白

        FigureCanvas.__init__(self, self.fig)  # 初始化父类
        self.setParent(parent)

        self.axes = self.fig.add_subplot(111)  # 调用figure下面的add_subplot方法,类似于matplotlib.pyplot下面的subplot方法
        self.axes.spines['top'].set_visible(False)  # 去掉上面的横线
        self.axes.spines['right'].set_visible(False)
        self.axes.set_xlim(xlim)
        self.axes.set_ylim(ylim)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值