python3+PyQt5实现自定义窗口部件Counters


Posted in Python onApril 20, 2018

本文通过Python3+PyQt5实现自定义部件?Counters自定 窗口部件。这个窗口是3*3的网格。本文有两个例子如下:

/home/yrd/eric_workspace/chap11/counters.py。
/home/yrd/eric_workspace/chap11/counters_dnd.py

第二个例子在第一个例子的基础上实现能通过鼠标拖拽球到不同的网格中。

/home/yrd/eric_workspace/chap11/counters.py

#!/usr/bin/env python3

from PyQt5.QtCore import (QRectF, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QSizePolicy,QWidget)
from PyQt5.QtGui import QPainter,QPen

BLANK, RED, YELLOW = range(3)


class CountersWidget(QWidget):

  def __init__(self, parent=None):
    super(CountersWidget, self).__init__(parent)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                    QSizePolicy.Expanding))
    self.grid = [[BLANK] * 3 for i in range(3)]
    self.selected = [0, 0]
    self.setMinimumSize(self.minimumSizeHint())


  def sizeHint(self):
    return QSize(200, 200)


  def minimumSizeHint(self):
    return QSize(100, 100)


  def mousePressEvent(self, event):
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    if event.x() < xOffset:
      x = 0
    elif event.x() < 2 * xOffset:
      x = 1
    else:
      x = 2
    if event.y() < yOffset:
      y = 0
    elif event.y() < 2 * yOffset:
      y = 1
    else:
      y = 2
    cell = self.grid[x][y]
    if cell == BLANK:
      cell = RED
    elif cell == RED:
      cell = YELLOW
    else:
      cell = BLANK
    self.grid[x][y] = cell
    self.selected = [x, y]
    self.update()


  def keyPressEvent(self, event):
    if event.key() == Qt.Key_Left:
      self.selected[0] = (2 if self.selected[0] == 0
                else self.selected[0] - 1)
    elif event.key() == Qt.Key_Right:
      self.selected[0] = (0 if self.selected[0] == 2
                else self.selected[0] + 1)
    elif event.key() == Qt.Key_Up:
      self.selected[1] = (2 if self.selected[1] == 0
                else self.selected[1] - 1)
    elif event.key() == Qt.Key_Down:
      self.selected[1] = (0 if self.selected[1] == 2
                else self.selected[1] + 1)
    elif event.key() == Qt.Key_Space:
      x, y = self.selected
      cell = self.grid[x][y]
      if cell == BLANK:
        cell = RED
      elif cell == RED:
        cell = YELLOW
      else:
        cell = BLANK
      self.grid[x][y] = cell
    self.update()


  def paintEvent(self, event=None):
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing, True)
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    for x in range(3):
      for y in range(3):
        cell = self.grid[x][y]
        rect = (QRectF(x * xOffset, y * yOffset,
            xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5))
        color = None
        if cell == RED:
          color = Qt.red
        elif cell == YELLOW:
          color = Qt.yellow
        if color is not None:
          painter.save()
          painter.setPen(Qt.black)
          painter.setBrush(color)
          painter.drawEllipse(rect.adjusted(2, 2, -2, -2))
          painter.restore()
        if [x, y] == self.selected:
          painter.setPen(QPen(Qt.blue, 3))
        else:
          painter.setPen(Qt.black)
        painter.drawRect(rect)


if __name__ == "__main__":
  import sys

  app = QApplication(sys.argv)
  form = CountersWidget()
  form.setWindowTitle("Counters")
  form.show()
  app.exec_()

/home/yrd/eric_workspace/chap11/counters_dnd.py

#!/usr/bin/env python3

from PyQt5.QtCore import (QRectF, QSize, Qt)
from PyQt5.QtWidgets import (QApplication, QSizePolicy,QWidget)
from PyQt5.QtGui import QPainter,QPen,QPixmap,QCursor
BLANK, RED, YELLOW = range(3)


class CountersWidget(QWidget):

  def __init__(self, parent=None):
    super(CountersWidget, self).__init__(parent)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                    QSizePolicy.Expanding))
    self.grid = [[BLANK] * 3 for i in range(3)]
    self.selected = [0, 0]
    self.setMinimumSize(self.minimumSizeHint())


  def sizeHint(self):
    return QSize(200, 200)


  def minimumSizeHint(self):
    return QSize(100, 100)


  def _xFromEventX(self, event):
    xOffset = self.width() / 3
    if event.x() < xOffset:
      x = 0
    elif event.x() < 2 * xOffset:
      x = 1
    else:
      x = 2
    return x


  def _yFromEventY(self, event):
    yOffset = self.width() / 3
    if event.y() < yOffset:
      y = 0
    elif event.y() < 2 * yOffset:
      y = 1
    else:
      y = 2
    return y


  def mouseDoubleClickEvent(self, event):
    x = self._xFromEventX(event)
    y = self._yFromEventY(event)
    cell = self.grid[x][y]
    if cell == BLANK:
      cell = RED
    elif cell == RED:
      cell = YELLOW
    else:
      cell = BLANK
    self.grid[x][y] = cell
    self.selected = [x, y]
    self.update()


  def keyPressEvent(self, event):
    if event.key() == Qt.Key_Left:
      self.selected[0] = (2 if self.selected[0] == 0
                else self.selected[0] - 1)
    elif event.key() == Qt.Key_Right:
      self.selected[0] = (0 if self.selected[0] == 2
                else self.selected[0] + 1)
    elif event.key() == Qt.Key_Up:
      self.selected[1] = (2 if self.selected[1] == 0
                else self.selected[1] - 1)
    elif event.key() == Qt.Key_Down:
      self.selected[1] = (0 if self.selected[1] == 2
                else self.selected[1] + 1)
    elif event.key() == Qt.Key_Space:
      x, y = self.selected
      cell = self.grid[x][y]
      if cell == BLANK:
        cell = RED
      elif cell == RED:
        cell = YELLOW
      else:
        cell = BLANK
      self.grid[x][y] = cell
    self.update()


  def paintEvent(self, event=None):
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing, True)
    xOffset = self.width() / 3
    yOffset = self.height() / 3
    for x in range(3):
      for y in range(3):
        cell = self.grid[x][y]
        rect = (QRectF(x * xOffset, y * yOffset,
            xOffset, yOffset).adjusted(0.5, 0.5, -0.5, -0.5))
        color = None
        if cell == RED:
          color = Qt.red
        elif cell == YELLOW:
          color = Qt.yellow
        if color is not None:
          painter.save()
          painter.setPen(Qt.black)
          painter.setBrush(color)
          painter.drawEllipse(rect.adjusted(2, 2, -2, -2))
          painter.restore()
        if [x, y] == self.selected:
          painter.setPen(QPen(Qt.blue, 3))
        else:
          painter.setPen(Qt.black)
        painter.drawRect(rect)


  def mousePressEvent(self, event):
    self.x = self._xFromEventX(event)
    self.y = self._yFromEventY(event)
    cell = self.grid[self.x][self.y]
    color = Qt.darkGray
    if cell == RED:
      color = Qt.red
    elif cell == YELLOW:
      color = Qt.yellow
    pixmap = QPixmap(12, 12)
    pixmap.fill(color)
    self.setCursor(QCursor(pixmap))


  def mouseReleaseEvent(self, event):
    x = self._xFromEventX(event)
    y = self._yFromEventY(event)
    if self.x != x or self.y != y:
      cell = self.grid[self.x][self.y]
      self.grid[self.x][self.y] = BLANK
      self.grid[x][y] = cell
      self.selected = [x, y]
      self.update()
    self.setCursor(Qt.ArrowCursor)


if __name__ == "__main__":
  import sys

  app = QApplication(sys.argv)
  form = CountersWidget()
  form.setWindowTitle("Counters")
  form.show()
  app.exec_()

运行结果:

python3+PyQt5实现自定义窗口部件Counters

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现过滤单个Android程序日志脚本分享
Jan 16 Python
Python实现将罗马数字转换成普通阿拉伯数字的方法
Apr 19 Python
Python简单计算文件MD5值的方法示例
Apr 11 Python
谈一谈基于python的面向对象编程基础
May 21 Python
python关于调用函数外的变量实例
Dec 26 Python
Python 识别12306图片验证码物品的实现示例
Jan 20 Python
Python实现检测文件的MD5值来查找重复文件案例
Mar 12 Python
使用Python和百度语音识别生成视频字幕的实现
Apr 09 Python
python读取图像矩阵文件并转换为向量实例
Jun 18 Python
python属于软件吗
Jun 18 Python
scrapy中如何设置应用cookies的方法(3种)
Sep 22 Python
Python pyecharts案例超市4年数据可视化分析
Aug 14 Python
Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作
Apr 20 #Python
python3+PyQt5实现支持多线程的页面索引器应用程序
Apr 20 #Python
python3+PyQt5+Qt Designer实现扩展对话框
Apr 20 #Python
pandas获取groupby分组里最大值所在的行方法
Apr 20 #Python
pandas多级分组实现排序的方法
Apr 20 #Python
Python PyQt4实现QQ抽屉效果
Apr 20 #Python
Python在groupby分组后提取指定位置记录方法
Apr 20 #Python
You might like
自动分页的不完整解决方案
2007/01/12 PHP
用php简单实现加减乘除计算器
2014/01/06 PHP
分享一个Laravel好用的Cache宏
2015/03/02 PHP
JavaScript实现滚动栏效果的方法
2015/04/27 PHP
PHP的Yii框架中Model模型的学习教程
2016/03/29 PHP
网页加载时页面显示进度条加载完成之后显示网页内容
2012/12/23 Javascript
通过js获取div的background-image属性
2013/10/15 Javascript
jquery鼠标停止移动事件
2013/12/21 Javascript
jquery中load方法的用法及注意事项说明
2014/02/22 Javascript
JavaScript声明变量名的语法规则
2015/07/10 Javascript
javascript简单实现等比例缩小图片的方法
2016/07/27 Javascript
jquery插件ContextMenu设置右键菜单
2017/03/13 Javascript
jQuery实现文章图片弹出放大效果
2017/04/06 jQuery
ReactNative之键盘Keyboard的弹出与消失示例
2017/07/11 Javascript
使用JavaScript开发跨平台的桌面应用详解
2017/07/27 Javascript
Vue中使用 setTimeout() setInterval()函数的问题
2018/09/13 Javascript
详解ES6 CLASS在微信小程序中的应用实例
2020/04/24 Javascript
python常规方法实现数组的全排列
2015/03/17 Python
python3中str(字符串)的使用教程
2017/03/23 Python
详细分析python3的reduce函数
2017/12/05 Python
python flask中静态文件的管理方法
2018/03/20 Python
python实现爬取图书封面
2018/07/05 Python
详解pyenv下使用python matplotlib模块的问题解决
2018/11/29 Python
python中partial()基础用法说明
2018/12/30 Python
实例介绍Python中整型
2019/02/11 Python
Django接收post前端返回的json格式数据代码实现
2019/07/31 Python
python读取指定字节长度的文本方法
2019/08/27 Python
OpenCV Python实现图像指定区域裁剪
2021/03/12 Python
英国标志性奢侈品牌:Burberry
2016/07/28 全球购物
Prototype是怎么扩展DOM的
2014/10/01 面试题
数控专业个人求职信范例
2013/11/29 职场文书
八年级英语教学反思
2014/01/09 职场文书
六年级学生评语
2014/04/22 职场文书
影视广告专业求职信
2014/09/02 职场文书
2014年药店店长工作总结
2014/11/17 职场文书
导游词之新疆尼雅遗址
2019/10/16 职场文书