我想创建一个类似于这个的摇杆小部件。
我的当前实现使用 QToolButton()
来表示侧边箭头,但我不确定如何创建中间的圆圈。当用户单击中间点并将其拖向箭头时,应该会注册移动。我考虑使用 paintEvent()
和 drawEclipse()
或者甚至 QDial()
,但我不确定如何做到这一点。
from PyQt4 import QtCore, QtGui
import sys
class JoystickWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(JoystickWidget, self).__init__(parent)
self.field_joystick_up_button = QtGui.QToolButton()
self.field_joystick_up_button.setArrowType(QtCore.Qt.UpArrow)
self.field_joystick_up_button.clicked.connect(self.joystick_up)
self.field_joystick_up_button.setFixedWidth(75)
self.field_joystick_down_button = QtGui.QToolButton()
self.field_joystick_down_button.setArrowType(QtCore.Qt.DownArrow)
self.field_joystick_down_button.clicked.connect(self.joystick_down)
self.field_joystick_down_button.setFixedWidth(75)
self.field_joystick_right_button = QtGui.QToolButton()
self.field_joystick_right_button.setArrowType(QtCore.Qt.RightArrow)
self.field_joystick_right_button.clicked.connect(self.joystick_right)
self.field_joystick_right_button.setFixedWidth(75)
self.field_joystick_left_button = QtGui.QToolButton()
self.field_joystick_left_button.setArrowType(QtCore.Qt.LeftArrow)
self.field_joystick_left_button.clicked.connect(self.joystick_left)
self.field_joystick_left_button.setFixedWidth(75)
self.joystick_layout = QtGui.QVBoxLayout()
self.joystick_layout.addWidget(self.field_joystick_up_button,alignment=QtCore.Qt.AlignCenter)
self.joystick_layout_row = QtGui.QHBoxLayout()
self.joystick_layout_row.addWidget(self.field_joystick_left_button)
self.joystick_layout_row.addWidget(self.field_joystick_right_button)
self.joystick_layout.addLayout(self.joystick_layout_row)
self.joystick_layout.addWidget(self.field_joystick_down_button,alignment=QtCore.Qt.AlignCenter)
def get_joystick_layout(self):
return self.joystick_layout
def joystick_up(self):
print("Up")
def joystick_down(self):
print("Down")
def joystick_right(self):
print("Right")
def joystick_left(self):
print("Left")
if __name__ == '__main__':
# Create main application window
app = QtGui.QApplication([])
app.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
mw = QtGui.QMainWindow()
mw.setWindowTitle('Joystick example')
# Create and set widget layout
# Main widget container
cw = QtGui.QWidget()
ml = QtGui.QGridLayout()
cw.setLayout(ml)
mw.setCentralWidget(cw)
# Create joystick
joystick = JoystickWidget()
ml.addLayout(joystick.get_joystick_layout(),0,0)
mw.show()
## Start Qt event loop unless running in interactive mode or using pyside.
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
QWidget
has been moved in another module since Qt5. Add the linefrom PyQt5.QtWidgets import QWidget
- Dimitry Ernot