如何将图片从QListview添加到QGraphicsView? (带拖放)

时间:2019-04-20 18:54:04

标签: python pyqt pyqt5 qgraphicsview qlistview

首先,我创建QListview类。然后,我将项目添加到QListview中。之后,我创建QGraphicsView类。我想通过拖放将项目的图片(由QListview创建)传输到QGraphicsView。我有个问题。我无法将项目的图片班级转移到班级。我的代码就是这样

URL::asset('resources/js/app.js')

QGraphicsView

localhost:8000/resources/js/app.js

1 个答案:

答案 0 :(得分:1)

由于模型默认已经具有一个“ application / x-qabstractitemmodeldatalist”,因此无需创建新的模仿类型,因此在这种情况下,我将仅在QGraphicsView中创建一个虚拟模型来接收数据,从而能够在QGraphicsView中重用它。

from PyQt5 import QtCore, QtGui, QtWidgets


class PartsList(QtWidgets.QListView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setGridSize(QtCore.QSize(108, 80))
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
        self._model = QtGui.QStandardItemModel(self)
        self.setModel(self._model)
        path = QtCore.QStandardPaths.writableLocation(
            QtCore.QStandardPaths.PicturesLocation
        )
        d = QtCore.QDir(path)
        formats = [
            "*.{}".format(fm.data().decode())
            for fm in QtGui.QImageReader.supportedImageFormats()
        ]
        for info in d.entryInfoList(formats, QtCore.QDir.Files):
            part = QtGui.QStandardItem(info.filePath())
            pixmap = QtGui.QPixmap(info.absoluteFilePath())
            part.setData(pixmap, QtCore.Qt.DecorationRole)
            self._model.appendRow(part)


class SchematicView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super().__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        self.setScene(scene)
        self.setSceneRect(0, 0, 1, 1)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat(
            "application/x-qabstractitemmodeldatalist"
        ):
            event.acceptProposedAction()

    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat(
            "application/x-qabstractitemmodeldatalist"
        ):
            event.acceptProposedAction()

    def dropEvent(self, event):
        sp = self.mapToScene(event.pos())
        dummy_model = QtGui.QStandardItemModel()
        dummy_model.dropMimeData(
            event.mimeData(), event.dropAction(), 0, 0, QtCore.QModelIndex()
        )
        for r in range(dummy_model.rowCount()):
            for c in range(dummy_model.columnCount()):
                ix = dummy_model.index(r, c)
                pixmap = ix.data(QtCore.Qt.DecorationRole)
                pixmap_item = self.scene().addPixmap(pixmap)
                pixmap_item.setPos(sp)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    hlay = QtWidgets.QHBoxLayout(w)
    pl = PartsList()
    sv = SchematicView()
    hlay.addWidget(pl)
    hlay.addWidget(sv)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

如果您仍要继续使用其他mimetype,则在支持QListView之类的模型的视图中,正确的选择是向mimeData添加新格式:

from PyQt5 import QtCore, QtGui, QtWidgets


class PartsList(QtWidgets.QListView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setGridSize(QtCore.QSize(108, 80))
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
        self._model = LibraryModel(self)
        self.setModel(self._model)
        path = QtCore.QStandardPaths.writableLocation(
            QtCore.QStandardPaths.PicturesLocation
        )
        d = QtCore.QDir(path)
        formats = [
            "*.{}".format(fm.data().decode())
            for fm in QtGui.QImageReader.supportedImageFormats()
        ]
        for info in d.entryInfoList(formats, QtCore.QDir.Files):
            part = self.__getPartItem(info.filePath())
            self._model.appendRow(part)

    def __getPartItem(self, name):
        part = QtGui.QStandardItem()
        pixmap = QtGui.QPixmap(name)
        part.setData(pixmap, QtCore.Qt.DecorationRole)
        part.setText(name)
        part.setEditable(False)
        return part


class LibraryModel(QtGui.QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setColumnCount(1)

    def mimeTypes(self):
        return super().mimeTypes() + ["part/name"]

    def mimeData(self, indexes):
        data = super().mimeData(indexes)
        encoded = QtCore.QByteArray()
        stream = QtCore.QDataStream(encoded, QtCore.QIODevice.WriteOnly)
        for ix in indexes:
            stream << ix.data(QtCore.Qt.DecorationRole)
        data.setData("part/name", encoded)
        return data


class SchematicView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super().__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        self.setScene(scene)
        self.setSceneRect(0, 0, 1, 1)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat("part/name"):
            event.acceptProposedAction()

    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat("part/name"):
            event.acceptProposedAction()

    def dropEvent(self, event):
        sp = self.mapToScene(event.pos())
        fmt = "part/name"
        data = event.mimeData()
        if data.hasFormat(fmt):
            encoded = data.data(fmt)
            stream = QtCore.QDataStream(encoded, QtCore.QIODevice.ReadOnly)
            pixmap = QtGui.QPixmap()
            while not stream.atEnd():
                stream >> pixmap
                pixmap_item = self.scene().addPixmap(pixmap)
                pixmap_item.setPos(sp)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    hlay = QtWidgets.QHBoxLayout(w)
    pl = PartsList()
    sv = SchematicView()
    hlay.addWidget(pl)
    hlay.addWidget(sv)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())