python之PyQt按钮右键菜单功能的实现代码

所属分类: 脚本专栏 / python 阅读数: 922
收藏 0 赞 0 分享

实现效果如下图:

这篇文字主要写了两方面的内容:

第一是按钮的自定义,第二是右键菜单的使用,不仅是按钮的右键菜单,其他一些控件的右键菜单也可以类似创建和使用。

关于右键菜单则是QMenu的一些使用方法有:

样式表的使用:

self.setStyleSheet("QMenu{background:purple;}"
              "QMenu{border:1px solid lightgray;}"
              "QMenu{border-color:green;}"
              "QMenu::item{padding:0px 40px 0px 20px;}"
              "QMenu::item{height:30px;}"  
              "QMenu::item{color:blue;}"
              "QMenu::item{background:white;}"
              "QMenu::item{margin:1px 0px 0px 0px;}"
              "QMenu::item:selected:enabled{background:lightgray;}"
              "QMenu::item:selected:enabled{color:white;}"  
              "QMenu::item:selected:!enabled{background:transparent;}"
              "QMenu::separator{height:50px;}"
              "QMenu::separator{width:1px;}"
              "QMenu::separator{background:white;}"
              "QMenu::separator{margin:1px 1px 1px 1px;}"  
              "QMenu#menu{background:white;}"
              "QMenu#menu{border:1px solid lightgray;}"
              "QMenu#menu::item{padding:0px 40px 0px 30px;}"
              "QMenu#menu::item{height:25px;}"
              "QMenu#menu::item:selected:enabled{background:lightgray;}"
              "QMenu#menu::item:selected:enabled{color:white;}"
              "QMenu#menu::item:selected:!enabled{background:transparent;}"
              "QMenu#menu::separator{height:1px;}"
              "QMenu#menu::separator{background:lightgray;}"
              "QMenu#menu::separator{margin:2px 0px 2px 0px;}"
              "QMenu#menu::indicator {padding:10px;}"
                            )

右键菜单的创建和菜单的信号槽:

def createContextMenu(self): 
    ''''' 
    创建右键菜单 
    ''' 
    # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu 
    # 否则无法使用customContextMenuRequested信号 
    self.setContextMenuPolicy(Qt.CustomContextMenu) 
    self.customContextMenuRequested.connect(self.showContextMenu) 
    # 创建QMenu 
    self.contextMenu = QMenu(self) 
    self.actionA = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作A') 
    self.actionB = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作B') 
    self.actionC = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作C') 
    #添加二级菜单
    self.second = self.contextMenu.addMenu(QIcon("images/0.png"),u"| 二级菜单") 
    self.actionD = self.second.addAction(QIcon("images/0.png"),u'| 动作A')
    self.actionE = self.second.addAction(QIcon("images/0.png"),u'| 动作B')
    self.actionF = self.second.addAction(QIcon("images/0.png"),u'| 动作C')
    # 将动作与处理函数相关联 
    # 这里为了简单,将所有action与同一个处理函数相关联, 
    # 当然也可以将他们分别与不同函数关联,实现不同的功能 
    self.actionA.triggered.connect(self.actionHandler) 
    self.actionB.triggered.connect(self.actionHandler) 
    self.actionC.triggered.connect(self.actionHandler) 
    self.actionD.triggered.connect(self.actionHandler) 
    self.actionE.triggered.connect(self.actionHandler) 
    self.actionF.triggered.connect(self.actionHandler) 

菜单的显示位置:

self.contextMenu.exec_(QCursor.pos()) #在鼠标位置显示

关于按钮的自定义,则包括了一些事件的重新定义和对按钮的ui界面的重新设计和绘制,就不一一列举了。
下面是一个demo包括了按钮的自定义,右键菜单的创建和使用,包括两个文件,图片可以随便找一个,不要过大或者过小就行:

mybutton.py
# -*- coding: utf-8 -*- 
from PyQt4.QtCore import Qt, QRect
from PyQt4.QtGui import QPushButton, QPainter, QPainterPath, QPen, QColor, QPixmap, QIcon, QBrush, QCursor,QMenu
class MenuButton(QPushButton):
  def __init__(self,parent = None):
    super(MenuButton,self).__init__(parent)
    self.setStyleSheet("QMenu{background:purple;}"
              "QMenu{border:1px solid lightgray;}"
              "QMenu{border-color:green;}"
              "QMenu::item{padding:0px 40px 0px 20px;}"
              "QMenu::item{height:30px;}"  
              "QMenu::item{color:blue;}"
              "QMenu::item{background:white;}"
              "QMenu::item{margin:1px 0px 0px 0px;}"
              "QMenu::item:selected:enabled{background:lightgray;}"
              "QMenu::item:selected:enabled{color:white;}"  
              "QMenu::item:selected:!enabled{background:transparent;}"
              "QMenu::separator{height:50px;}"
              "QMenu::separator{width:1px;}"
              "QMenu::separator{background:white;}"
              "QMenu::separator{margin:1px 1px 1px 1px;}"  
              "QMenu#menu{background:white;}"
              "QMenu#menu{border:1px solid lightgray;}"
              "QMenu#menu::item{padding:0px 40px 0px 30px;}"
              "QMenu#menu::item{height:25px;}"
              "QMenu#menu::item:selected:enabled{background:lightgray;}"
              "QMenu#menu::item:selected:enabled{color:white;}"
              "QMenu#menu::item:selected:!enabled{background:transparent;}"
              "QMenu#menu::separator{height:1px;}"
              "QMenu#menu::separator{background:lightgray;}"
              "QMenu#menu::separator{margin:2px 0px 2px 0px;}"
              "QMenu#menu::indicator {padding:10px;}"
                            )
    self.hovered = False
    self.pressed = False
    self.pressedIcon = QIcon()
    self.color = QColor(Qt.gray)
    self.opacity = 1.0
    self.count = 0
#     self.setAutoFillBackground(True)
#     self.setStyleSheet("#Check {background-color: rgb(255, 255, 255);}");
    self.createContextMenu() 
    self.count = 0
  def createContextMenu(self): 
    ''''' 
              创建右键菜单 
    ''' 
    # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu 
    # 否则无法使用customContextMenuRequested信号 
    self.setContextMenuPolicy(Qt.CustomContextMenu) 
    self.customContextMenuRequested.connect(self.showContextMenu) 
    # 创建QMenu 
    self.contextMenu = QMenu(self) 
    self.actionA = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作A') 
    self.actionB = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作B') 
    self.actionC = self.contextMenu.addAction(QIcon("images/0.png"),u'| 动作C') 
    #添加二级菜单
    self.second = self.contextMenu.addMenu(QIcon("images/0.png"),u"| 二级菜单") 
    self.actionD = self.second.addAction(QIcon("images/0.png"),u'| 动作A')
    self.actionE = self.second.addAction(QIcon("images/0.png"),u'| 动作B')
    self.actionF = self.second.addAction(QIcon("images/0.png"),u'| 动作C')
    # 将动作与处理函数相关联 
    # 这里为了简单,将所有action与同一个处理函数相关联, 
    # 当然也可以将他们分别与不同函数关联,实现不同的功能 
    self.actionA.triggered.connect(self.actionHandler) 
    self.actionB.triggered.connect(self.actionHandler) 
    self.actionC.triggered.connect(self.actionHandler) 
    self.actionD.triggered.connect(self.actionHandler) 
    self.actionE.triggered.connect(self.actionHandler) 
    self.actionF.triggered.connect(self.actionHandler)  
  def showContextMenu(self, pos): 
    ''''' 
    右键点击时调用的函数 
    ''' 
    self.count+=1
    # 菜单显示前,将它移动到鼠标点击的位置 
    self.contextMenu.exec_(QCursor.pos()) #在鼠标位置显示
    #self.contextMenu.show() 
    print self.count
  def actionHandler(self): 
    ''''' 
    菜单中的具体action调用的函数 
    ''' 
    if self.count%3==1:
      self.setText(u"first")
    elif self.count%3==2:
      self.setText(u"second")
    elif self.count%3==0:
      self.setText(u"third")
  def setEnterCursorType(self, Type):
    self.cursorType = Type
  def setColor(self,color):
    self.color = color
  def setOpacitys(self,opacity):
    self.opacity = opacity
#     self.setOpacity(0.5)
  def enterEvent(self,event):
    self.hovered = True
    self.repaint()
    QPushButton.enterEvent(self,event)
  def leaveEvent(self,event):
    self.hovered = False
    self.repaint()
    self.setCursor(QCursor(Qt.ArrowCursor)) 
    QPushButton.leaveEvent(self,event)
  def mousePressEvent(self, event):
    self.pressed = True
    self.repaint()
    QPushButton.mousePressEvent(self,event)
  def mouseReleaseEvent(self, event):
    self.pressed = False
    self.repaint()
    QPushButton.mouseReleaseEvent(self,event)
  def paintEvent(self,event):
    painter = QPainter(self)
    btnRect = self.geometry()
    iconRect = self.iconSize()
    color = QColor(Qt.black)
    if self.hovered:
      color = self.color
    if self.pressed:
      color = self.color.darker(120)
    painter.setPen(QPen(QColor(Qt.lightGray),2))
    outline = QPainterPath()
    outline.addRoundedRect(0, 0, btnRect.width(), btnRect.height(), 0, 0)
    painter.setOpacity(1)
    painter.drawPath(outline)
    painter.setBrush(QBrush(color)) 
    painter.setOpacity(self.opacity)
    painter_path = QPainterPath()
    painter_path.addRoundedRect(1, 1, btnRect.width() - 2, btnRect.height() - 2, 0, 0)
    if self.hovered:
      painter.setClipPath(painter_path)
      painter.drawRoundedRect(1, 1, btnRect.width() - 2, btnRect.height() - 2, 0, 0)
    painter.setOpacity(1)    
    iconPos,textPos = self.calIconTextPos(btnRect, iconRect)
    # 重画文本
    if not self.text().isNull():
      painter.setFont(self.font())
      painter.setPen(QPen(QColor(Qt.black),2))
      painter.drawText(textPos.x(), textPos.y(), textPos.width(), textPos.height(), Qt.AlignCenter, self.text())
      # 重画图标
    if not self.icon().isNull():
      painter.drawPixmap(iconPos, QPixmap(self.icon().pixmap(self.iconSize())))
  # 计算图标和文本大小位置
  def calIconTextPos(self,btnSize,iconSize):
    if self.text().isNull():
      iconWidth = iconSize.width()*3/5
      iconHeight = iconSize.height()*3/5
    else:
      iconWidth = iconSize.width()
      iconHeight = iconSize.height() - 50
    iconX = (btnSize.width()-iconWidth)/2
    iconY = (btnSize.height()-iconHeight)/2
    iconPos = QRect()
    iconPos.setX(iconX)
    iconPos.setY(iconY)
    iconPos.setWidth(iconWidth)
    iconPos.setHeight(iconHeight)
    textPos = QRect()
    if not self.text().isNull():
      textPos.setX(iconX)
      textPos.setY(btnSize.height()- 50)
      textPos.setWidth(iconWidth)
      textPos.setHeight(50)
    return (iconPos,textPos)
1
buttontest.py
# -*- coding: utf-8 -*- 
from mybutton import MenuButton
import sys
from PyQt4.QtCore import QTextCodec, QSize, SIGNAL
from PyQt4.QtGui import QDialog, QIcon, QHBoxLayout, QApplication
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))
class TestDialog(QDialog):
  def __init__(self,parent=None):
    super(TestDialog,self).__init__(parent)
    self.setFixedSize(200,200)
    self.firMybutton = MenuButton()
    self.firMybutton.setFixedSize(QSize(100,100))
    self.firMybutton.setIcon(QIcon("windows.png"))
    self.firMybutton.setIconSize(QSize(100,100))
    #self.firMybutton.setText(self.tr("确萨"))
    self.connect(self.firMybutton, SIGNAL("clicked()"),self.cancel)
    myLayout = QHBoxLayout()
    myLayout.addWidget(self.firMybutton)
    self.setLayout(myLayout)
  def cancel(self):
    self.close()
app=QApplication(sys.argv)
dialog=TestDialog()
dialog.show()
app.exec_()

以上所述是小编给大家介绍的python之PyQt按钮右键菜单功能的实现代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

更多精彩内容其他人还在看

Python常见加密模块用法分析【MD5,sha,crypt模块】

这篇文章主要介绍了Python常见加密模块用法,结合实例形式较为详细的分析了MD5,sha与crypt模块加密的相关实现方法与操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python向日志输出中添加上下文信息

这篇文章主要介绍了Python向日志输出中添加上下文信息的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现的简单dns查询功能示例

这篇文章主要介绍了Python实现的简单dns查询功能,结合实例形式分析了Python基于socket模块的dns信息查询实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

利用Anaconda完美解决Python 2与python 3的共存问题

Anaconda 是 Python 的一个发行版,如果把 Python 比作 Linux,那么 Anancoda 就是 CentOS 或者 Ubuntu,下面这篇文章主要给大家介绍了利用Anaconda完美解决Python 2与python 3共存问题的相关资料,文中介绍的非常详
收藏 0 赞 0 分享

Python随机读取文件实现实例

这篇文章主要介绍了Python随机读取文件的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

用生成器来改写直接返回列表的函数方法

下面小编就为大家带来一篇用生成器来改写直接返回列表的函数方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python爬虫入门教程--快速理解HTTP协议(一)

http协议是互联网里面最重要,最基础的协议之一,我们的爬虫需要经常和http协议打交道。下面这篇文章主要给大家介绍了关于python爬虫入门之快速理解HTTP协议的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

老生常谈Python进阶之装饰器

下面小编就为大家带来一篇老生常谈Python进阶之装饰器。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈Python基础之I/O模型

下面小编就为大家带来一篇浅谈Python基础之I/O模型。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python如何获取服务器硬件信息

这篇文章主要为大家详细介绍了python获取服务器硬件信息的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多