はんぎょねこの憂鬱

耳から変な汁が出てきた

PySide ドラッグでWidgetを移動させる

f:id:dungeonneko:20170525134629g:plain

import sys
from PySide import QtCore, QtGui

# ドラッグで動くWidget
class WidgetItem(QtGui.QLabel):
    def __init__(self):
        super().__init__('')
        self.setStyleSheet('border: 1px solid black; background-color: red;')
        self.setFixedSize(32, 32)
        self._drag = False
        self._offset = QtCore.QPoint(0, 0)

    def mousePressEvent(self, event):
        self._drag = True
        self._offset = event.pos()

    def mouseReleaseEvent(self, event):
        self._drag = False

    def mouseMoveEvent(self, event):
        if self._drag:
            self.move(self.mapToParent(event.pos() - self._offset))

app = QtGui.QApplication(sys.argv)

widget = QtGui.QWidget()
widget.setFixedSize(640, 480)
widget.setLayout(QtGui.QVBoxLayout())
layout = widget.layout()
item = WidgetItem()
layout.addWidget(item)
widget.show()
sys.exit(app.exec_())