Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PyQt4.QtGui import QWidget, QApplication, QPainter
- from PyQt4 import QtCore
- import sys
- class Joystick(QWidget):
- def __init__(self, parent=None):
- super(Joystick, self).__init__(parent)
- self.setFixedSize(100, 100)
- self._minimumX = -10
- self._maximumX = 20
- self._minimumY = -10
- self._maximumY = 10
- self.cursorPosition = QtCore.QPointF(10, 90)
- self.grabCursor = False
- def valueX(self):
- return (self.cursorPosition.x() - 10) * (self._maximumX - self._minimumX) / (self.width() - 20) + self._minimumX
- def valueY(self):
- return (self.cursorPosition.y() - 10) * (self._maximumY - self._minimumY) / (self.width() - 20) + self._minimumY
- def paintEvent(self, event):
- painter = QPainter(self)
- painter.setBrush(QtCore.Qt.lightGray)
- painter.setPen(QtCore.Qt.NoPen)
- painter.drawRect(0, 0, self.width(), self.height())
- painter.setBrush(QtCore.Qt.blue)
- painter.drawEllipse(self.cursorRect())
- def boundedCursor(self, position):
- def bound(low, high, value):
- return max(low, min(high, value))
- x = bound(10, self.width() - 10, position.x())
- y = bound(10, self.height() - 10, position.y())
- return QtCore.QPointF(x, y)
- def cursorRect(self):
- return QtCore.QRectF(-5, -5, 10, 10).translated(self.cursorPosition)
- def mousePressEvent(self, ev):
- self.grabCursor = self.cursorRect().contains(ev.pos())
- return super().mousePressEvent(ev)
- def mouseReleaseEvent(self, event):
- self.grabCursor = False
- self.update()
- def mouseMoveEvent(self, event):
- if self.grabCursor:
- print("Moving")
- self.cursorPosition = self.boundedCursor(event.pos())
- self.update()
- print(self.valueX(), self.valueY())
- if __name__ == '__main__':
- # Create main application window
- app = QApplication([])
- joystick = Joystick()
- joystick.show()
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement