I have a set of 3 list widgets all with drag and drop capabilities. I am looking to eliminate repeated code and am looking for some help. As you can see in my Dialog class I create 3 Image classes that are drag and drog lists. As of right now each List Widget corresponds to a connect function.
</code>self.connect(self.one, SIGNAL("dropped"), self.oneDropped)</pre>It seems to me that the function <code><pre class="CodeBlock"><code>def oneDropped()could be turned into a function where
<pre class="CodeBlock"><code>self.oneDropped
is an argument, but I am having trouble setting that up and could use some help. Here is my code.import sys import os from PyQt4 import uic from PyQt4.QtGui import * from PyQt4.QtCore import * class Image(QListWidget): def __init__(self, type, parent=None): super(Image, self).__init__(parent) self.setAcceptDrops(True) self.setIconSize(QSize(72, 72)) def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() links = [] for url in event.mimeData().urls(): links.append(str(url.toLocalFile())) self.emit(SIGNAL("dropped"), links) else: event.ignore() class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.ui = uic.loadUi('./qt/default.ui', self) self.one = Image(self) self.two = Image(self) self.three = Image(self) self.connect(self.one, SIGNAL("dropped"), self.oneDropped) self.connect(self.two, SIGNAL("dropped"), self.twoDropped) self.connect(self.three, SIGNAL("dropped"), self.threeDropped) self.baseimage_layout.addWidget(self.one) self.redimage_layout.addWidget(self.two) self.greenimage_layout.addWidget(self.three) def oneDropped(self, l): for url in l: if os.path.exists(url): print(url) icon = QIcon(url) pixmap = icon.pixmap(72, 72) icon = QIcon(pixmap) item = QListWidgetItem(url, self.one) item.setIcon(icon) def twoDropped(self, l): for url in l: if os.path.exists(url): print(url) icon = QIcon(url) pixmap = icon.pixmap(72, 72) icon = QIcon(pixmap) item = QListWidgetItem(url, self.two) item.setIcon(icon) def threeDropped(self, l): for url in l: if os.path.exists(url): print(url) icon = QIcon(url) pixmap = icon.pixmap(72, 72) icon = QIcon(pixmap) item = QListWidgetItem(url, self.three) item.setIcon(icon) def main(): app = QApplication(sys.argv) form = Dialog() form.show() app.exec_() if __name__=="__main__": main()
Replies
http://stackoverflow.com/a/940655/4206247
No idea if this works, but it's an idea: