简体   繁体   English

如何在qlistwidget上获取从dropEvent创建的项目

[英]How to get the item created from dropEvent on a qlistwidget

So I'm trying to copy a selected item from one QListWidget to another using drag and drop. 所以我试图使用拖放功能将选定的项目从一个QListWidget复制到另一个。

Anyway I could probably hack together what I need to by passing serialized parameters using item.setData but I can't figure out a straight forward way to get a handle on the new item being created in the second listWidget. 无论如何,我可能通过使用item.setData传递序列化参数来破解我需要的东西,但是我无法想出一个直接的方法来获取在第二个listWidget中创建的新项目的句柄。

I guess I could look at all the items in the second QListWidget and somehow determine which one was just created but it seems like there should be an easier way to know which item is being created by the drop event. 我想我可以查看第二个QListWidget中的所有项目,并以某种方式确定哪一个刚刚创建,但似乎应该有一种更简单的方法来了解drop事件正在创建哪个项目。

import sys
from PyQt4 import QtGui , QtCore


def main():

    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    layout=QtGui.QHBoxLayout(w)
    dragList=DragDropListWidget()
    layout.addWidget(dragList)
    dragList.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
    dragList.name='dragList'
    dragList.populate(['one','two','three'])
    dragList2=DragDropListWidget()
    dragList2.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
    dragList2.name='dragList'


    layout.addWidget(dragList2)
    w.show()

    sys.exit(app.exec_())

class scriptsWidget(QtGui.QWidget):


    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)

        self.name=''

        self.widget_QHBoxLayout = QtGui.QHBoxLayout(self)
        self.widget_QHBoxLayout.setSpacing(0)
        self.widget_QHBoxLayout.setContentsMargins(0, 0, 0, 0)

        self.name_QLabel = QtGui.QLabel(self)
        self.widget_QHBoxLayout.addWidget(self.name_QLabel)

        self.user_QLabel = QtGui.QLabel(self)
        self.widget_QHBoxLayout.addWidget(self.user_QLabel)

        self.widget_QHBoxLayout.setSpacing(0)
        self.widget_QHBoxLayout.setContentsMargins(0, 0, 0, 0)



    def setName(self,name):
        self.name_QLabel.setText(name)
        self.name=name

    def setUser(self,user):
        self.user_QLabel.setText(user)

class customQListWidgetItem(QtGui.QListWidgetItem):


    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)
        self.name=''

    def setName(self,name):
        self.name=name   




class DragDropListWidget(QtGui.QListWidget):
    _drag_info = []
    def __init__(self, parent = None):

        super(DragDropListWidget, self).__init__(parent)


        self.name=''


    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()

        else:
            super(DragDropListWidget, self).dragMoveEvent(event)


    def dropEvent(self, event):
        print('dropEvent') 
        print event.mimeData().text()

        if event.mimeData().hasText():
            print event.mimeData().text()
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.emit(QtCore.SIGNAL("dropped"), links)

        else:
            event.setDropAction(QtCore.Qt.CopyAction)
            super(DragDropListWidget, self).dropEvent(event)
            items = []
            for index in xrange(self.count()):
                items.append(self.item(index))
                print self.item(index).data(QtCore.Qt.UserRole).toPyObject()



    def populate(self,items=[]):
        self.clear()
        for i in items:
            print(i)
            widget = scriptsWidget()
            widget.setName(i)
            widget.setUser('x')
            item = customQListWidgetItem()
            item.setName(i)
            data = (i)
            item.setData(QtCore.Qt.UserRole, data)
            self.addItem(item)
            self.setItemWidget(item,widget)



if __name__ == '__main__':
    main()

You can connect to the rowsInserted signal on the listview model 您可以连接到listview模型上的rowsInserted信号

class DragDropListWidget(...):

    def __init__(...):
        ...
        self._dropping = False
        self.model().rowsInserted.connect(self.on_rowsInserted)

    def on_rowsInserted(self, parent_index, start, end):
        if self._dropping:
            # Recently dropped items
            items = [self.item(i) for i in range(start, end + 1)]

    def dropEvent(self, event):
        self._dropping = True
        # code that drops the new rows
        ...
        self._dropping = False

Interesting .. well my solution ended up being to store a list of items in the second listwidget before and then do a comparison after the new item is added which works well enough and takes only a few lines of code. 有趣..好吧,我的解决方案最终是在第二个listwidget中存储项目列表,然后在添加新项目之后进行比较,该项目运行良好并且只需几行代码。 Then I pass the new item to a function that creates the item using the same classes that were used when it was created in the first listwidget and I passed serialized info about in .data(QtCore.Qt.UserRole) 然后我将新项目传递给一个函数,该函数使用在第一个listwidget中创建项目时使用的相同类来创建项目,并且我传递了.data中的序列化信息(QtCore.Qt.UserRole)

def dropEvent(self, event):
    if event.mimeData().hasText():
        event.setDropAction(QtCore.Qt.CopyAction)
        event.accept()
        links = []
        for url in event.mimeData().urls():
            links.append(str(url.toLocalFile()))
        self.emit(QtCore.SIGNAL("dropped"), links)

    else:
        event.setDropAction(QtCore.Qt.CopyAction)
        items = []
        for index in xrange(self.count()):
            items.append(self.item(index))

        super(DragDropListWidget, self).dropEvent(event)

        for index in xrange(self.count()):
            if self.item(index) not in items:
                self.populateDrop(self.item(index), index, [self.item(index).data(QtCore.Qt.UserRole).toPyObject()])

def populateDrop(self,item,row,items=[]):
    for i in items:
        widget = scriptsWidget()
        widget.setName(i)
        widget.setUser('x')
        self.takeItem(row)
        item = customQListWidgetItem()
        item.setName(i)
        item.setWhatsThis(i)
        data = (i)
        item.setData(QtCore.Qt.UserRole, data)
        self.insertItem (row, item)
        self.setItemWidget(item,widget)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM