在GUI编程中,拖拽操作即在不同的应用间拖拽对象以实现对象的移动
1、简单的拖拽
为了实现将行编辑器中的文本拖拽到按钮上,我们必须重写一些方法,所以我们在继承QtGui.QPushButton的基础上创造我们自己的BUTTON类
# -*- coding: utf-8 -*- """ ZetCode PySide tutorial This is a simple drag and drop example. author: Jan Bodnar website: zetcode.com last edited: August 2011 """ import sys from PySide import QtGui, QtCore class Button(QtGui.QPushButton): # 定义Button类,以实现拖拽操作 def __init__(self, title, parent): super(Button, self).__init__(title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, e): # 重写 拖 函数,定义好我们要接受的数据类型 if e.mimeData().hasFormat('text/plain'): e.accept() else: e.ignore() def dropEvent(self, e): # 重写 放 函数,具体实现一个改变按钮的文本的操作 self.setText(e.mimeData().text()) class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): qe = QtGui.QLineEdit('', self) qe.setDragEnabled(True) qe.move(30, 65) button = Button("Button", self) button.move(190, 65) self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Simple Drag & Drop') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()二、在下面的示例中,我们会证明 如何拖拽一个button,在本示例中,点击左键会显示 ‘press’,按压住右键可以拖拽按钮
# -*- coding: utf-8 -*- """ ZetCode PySide tutorial In this example, we drag and drop a button. author: Jan Bodnar website: zetcode.com last edited: August 2011 """ import sys from PySide import QtGui, QtCore class Button(QtGui.QPushButton): def __init__(self, title, parent): super(Button, self).__init__(title, parent) def mouseMoveEvent(self, e): if e.buttons() != QtCore.Qt.RightButton: return mimeData = QtCore.QMimeData() drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(e.pos() - self.rect().topLeft()) dropAction = drag.start(QtCore.Qt.MoveAction) def mousePressEvent(self, e): QtGui.QPushButton.mousePressEvent(self, e) if e.button() == QtCore.Qt.LeftButton: print 'press' class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setAcceptDrops(True) self.btn = Button('Button', self) self.btn.move(100, 65) self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Click or move') self.show() def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): position = e.pos() self.btn.move(position) e.setDropAction(QtCore.Qt.MoveAction) e.accept() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()