侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   442

实现效果如下图:

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

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

关于右键菜单则是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, QRectfrom PyQt4.QtGui import QPushButton, QPainter, QPainterPath, QPen, QColor, QPixmap, QIcon, QBrush, QCursor,QMenuclass 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)1buttontest.py# -*- coding: utf-8 -*- from mybutton import MenuButtonimport sysfrom PyQt4.QtCore import QTextCodec, QSize, SIGNALfrom PyQt4.QtGui import QDialog, QIcon, QHBoxLayout, QApplicationQTextCodec.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模拟键盘输入 切换键盘布局过程解析
    下一条:
    python PyQt5/Pyside2 按钮右击菜单实例代码
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客