Advertisement
robertvari

Custom Button

Mar 14th, 2019
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. from PySide2.QtWidgets import QWidget, QApplication
  2. from PySide2.QtGui import QPainter, QBrush, QColor, QFont
  3. from PySide2.QtCore import Signal, Qt
  4. import sys
  5.  
  6. class CustomButton(QWidget):
  7.     mouseClicked = Signal()
  8.  
  9.     def __init__(self):
  10.         super(CustomButton, self).__init__()
  11.         self.highlight = False
  12.         self.pressed = False
  13.  
  14.     def mousePressEvent(self, event):
  15.         print("Mouse clicked!")
  16.         self.pressed = True
  17.         self.mouseClicked.emit()
  18.  
  19.         self.repaint()
  20.  
  21.     def mouseReleaseEvent(self, event):
  22.         self.pressed = False
  23.         self.repaint()
  24.  
  25.     def paintEvent(self, event):
  26.         painter = QPainter()
  27.         painter.begin(self)
  28.  
  29.         self.drawWidget(painter)
  30.  
  31.         painter.end()
  32.  
  33.     def enterEvent(self, event):
  34.         self.highlight = True
  35.         QApplication.setOverrideCursor(Qt.PointingHandCursor)
  36.  
  37.         self.repaint()
  38.  
  39.     def leaveEvent(self, event):
  40.         self.highlight = False
  41.         QApplication.restoreOverrideCursor()
  42.  
  43.         self.repaint()
  44.  
  45.     def drawWidget(self, painter):
  46.         rect = self.rect()
  47.  
  48.         painter.setBrush(QBrush(QColor("green")))
  49.         if self.highlight:
  50.             painter.setBrush(QBrush(QColor("red")))
  51.  
  52.         if self.pressed:
  53.             painter.setBrush(QBrush(QColor("lightBlue")))
  54.  
  55.         painter.drawRect(rect)
  56.  
  57.         # create a custom pen with 5 pixel width and blue color
  58.         font = QFont()
  59.         font.setPointSize(30)
  60.         font.setFamily("consolas")
  61.         painter.setPen(QColor("blue"))
  62.         painter.setFont(font)
  63.  
  64.         painter.drawText(rect, Qt.AlignHCenter | Qt.AlignVCenter, "Hello World!")
  65.  
  66.  
  67. app = QApplication(sys.argv)
  68. win = CustomButton()
  69. win.show()
  70. app.exec_()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement