Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. from PyQt4.QtGui import QWidget, QApplication, QPainter
  2. from PyQt4 import QtCore
  3. import sys
  4.  
  5. class Joystick(QWidget):
  6. def __init__(self, parent=None):
  7. super(Joystick, self).__init__(parent)
  8. self.setFixedSize(100, 100)
  9.  
  10. self._minimumX = -10
  11. self._maximumX = 20
  12. self._minimumY = -10
  13. self._maximumY = 10
  14.  
  15. self.cursorPosition = QtCore.QPointF(10, 90)
  16. self.grabCursor = False
  17.  
  18. def valueX(self):
  19. return (self.cursorPosition.x() - 10) * (self._maximumX - self._minimumX) / (self.width() - 20) + self._minimumX
  20.  
  21. def valueY(self):
  22. return (self.cursorPosition.y() - 10) * (self._maximumY - self._minimumY) / (self.width() - 20) + self._minimumY
  23.  
  24. def paintEvent(self, event):
  25. painter = QPainter(self)
  26. painter.setBrush(QtCore.Qt.lightGray)
  27. painter.setPen(QtCore.Qt.NoPen)
  28. painter.drawRect(0, 0, self.width(), self.height())
  29. painter.setBrush(QtCore.Qt.blue)
  30. painter.drawEllipse(self.cursorRect())
  31.  
  32. def boundedCursor(self, position):
  33. def bound(low, high, value):
  34. return max(low, min(high, value))
  35. x = bound(10, self.width() - 10, position.x())
  36. y = bound(10, self.height() - 10, position.y())
  37. return QtCore.QPointF(x, y)
  38.  
  39. def cursorRect(self):
  40. return QtCore.QRectF(-5, -5, 10, 10).translated(self.cursorPosition)
  41.  
  42. def mousePressEvent(self, ev):
  43. self.grabCursor = self.cursorRect().contains(ev.pos())
  44. return super().mousePressEvent(ev)
  45.  
  46. def mouseReleaseEvent(self, event):
  47. self.grabCursor = False
  48. self.update()
  49.  
  50. def mouseMoveEvent(self, event):
  51. if self.grabCursor:
  52. print("Moving")
  53. self.cursorPosition = self.boundedCursor(event.pos())
  54. self.update()
  55. print(self.valueX(), self.valueY())
  56.  
  57. if __name__ == '__main__':
  58. # Create main application window
  59. app = QApplication([])
  60. joystick = Joystick()
  61. joystick.show()
  62. sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement