logo
down
shadow

pyqt QTreeWidget setItemWidget dissapears after drag/drop


pyqt QTreeWidget setItemWidget dissapears after drag/drop

By : user3851760
Date : October 15 2020, 11:12 PM
it should still fix some issue managed to get a relatively "working" fix in by writing my own treeDropEvent... however if someone has a more elegant solution, please feel free to share. the code below will solve anyone else's headaches for drag/drop with setItemWidgets in a tree, cheers.
code :


Share : facebook icon twitter icon
Drag and Drop imagebutton Dissapears behind different view

Drag and Drop imagebutton Dissapears behind different view


By : Ashvin Rajani
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You need to setup your "Sky" to handle drag events. You can do this with one line:
code :
 findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag());
pyqt QTreeWidget signal on item drop

pyqt QTreeWidget signal on item drop


By : user3353439
Date : March 29 2020, 07:55 AM
wish of those help I need to enable a button in my app whenever something is dropped to my custom QTreeWidget. , You could define a custom signal and emit it from dropEvent:
code :
class MyTreeWidget(QtGui.QTreeWidget):
    itemDropped = QtCore.pyqtSignal()

    def dropEvent(self, event): 
        if (event.mimeData().hasFormat('application/x-icon-and-text')):
            ...
            self.itemDropped.emit()
QListWidget drag and drop with a custom widget set via setItemWidget

QListWidget drag and drop with a custom widget set via setItemWidget


By : J. Robinson
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , To customize the QPixmap associated with the QDrag of QListWidget we must override the startDrag() method.
The main task is to get a QPixmap of the elements selected for it is created a QPixmap the size of the visible image of the viewport() that is transparent and then we paint them with QPixmap of each item selected for it we use QPainter.
code :
#ifndef LISTWIDGET_H
#define LISTWIDGET_H

#include <QListWidget>
#include <QDrag>
#include <QMimeData>
#include <QPainter>

class ListWidget : public QListWidget
{
protected:
    void startDrag(Qt::DropActions supportedActions){
        QDrag *drag = new QDrag(this);
        drag->setMimeData(model()->mimeData(selectedIndexes()));
        QPixmap pixmap(viewport()->visibleRegion().boundingRect().size());
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);
        for(QModelIndex index: selectedIndexes()){
            painter.drawPixmap(visualRect(index), viewport()->grab(visualRect(index)));
        }
        drag->setPixmap(pixmap);
        drag->setHotSpot(viewport()->mapFromGlobal(QCursor::pos()));
        drag->exec(supportedActions, Qt::MoveAction);
    }
};

#endif // LISTWIDGET_H
Reordering items in a QTreeWidget with Drag and Drop in PyQt

Reordering items in a QTreeWidget with Drag and Drop in PyQt


By : Rikard Karlsson
Date : March 29 2020, 07:55 AM
will help you You can add flags to individual tree widget items that control drag and drop behaviour (amongst other things). For instance, to prevent an item being a drop target, try something like this:
Qt Drag and drop between QTreeWidget

Qt Drag and drop between QTreeWidget


By : freever
Date : March 29 2020, 07:55 AM
I wish this helpful for you In order to perform this task we must distinguish if the action comes from himself or another widget for it is overwritten by the dropEvent method, this returns an event of type QDropEvent that has the method source() that returns the object that performed the action:
code :
def dropEvent(self, event):
    if event.source() == self:
        # move
    else:
        # copy
if event.source() == self:
    event.setDropAction(Qt.MoveAction)
    QTreeWidget.dropEvent(self, event)
row_1 | column_1 | number of valid roles | role_1_1 | value_1_1 | ... | role_n_1 | value_n_1 | row_2 | column_2 | ...
class TreeWidget(QTreeWidget):
    customMimeType = "application/x-customTreeWidgetdata"

    def mimeTypes(self):
        mimetypes = QTreeWidget.mimeTypes(self)
        mimetypes.append(TreeWidget.customMimeType)
        return mimetypes

    def startDrag(self, supportedActions):
        drag = QDrag(self)
        mimedata = self.model().mimeData(self.selectedIndexes())

        encoded = QByteArray()
        stream = QDataStream(encoded, QIODevice.WriteOnly)
        self.encodeData(self.selectedItems(), stream)
        mimedata.setData(TreeWidget.customMimeType, encoded)

        drag.setMimeData(mimedata)
        drag.exec_(supportedActions)

    def dropEvent(self, event):
        if event.source() == self:
            event.setDropAction(Qt.MoveAction)
            QTreeWidget.dropEvent(self, event)
        elif isinstance(event.source(), QTreeWidget):
            if event.mimeData().hasFormat(TreeWidget.customMimeType):
                encoded = event.mimeData().data(TreeWidget.customMimeType)
                parent = self.itemAt(event.pos())
                items = self.decodeData(encoded, event.source())
                for it in items:
                    item = QTreeWidgetItem(parent)
                    self.fillItem(it, item)
                    self.fillItems(it, item)
                event.acceptProposedAction()

    def fillItem(self, inItem, outItem):
        for col in range(inItem.columnCount()):
            for key in range(Qt.UserRole):
                role = Qt.ItemDataRole(key)
                outItem.setData(col, role, inItem.data(col, role))

    def fillItems(self, itFrom, itTo):
        for ix in range(itFrom.childCount()):
            it = QTreeWidgetItem(itTo)
            ch = itFrom.child(ix)
            self.fillItem(ch, it)
            self.fillItems(ch, it)

    def encodeData(self, items, stream):
        stream.writeInt32(len(items))
        for item in items:
            p = item
            rows = []
            while p is not None:
                rows.append(self.indexFromItem(p).row())
                p = p.parent()
            stream.writeInt32(len(rows))
            for row in reversed(rows):
                stream.writeInt32(row)
        return stream

    def decodeData(self, encoded, tree):
        items = []
        rows = []
        stream = QDataStream(encoded, QIODevice.ReadOnly)
        while not stream.atEnd():
            nItems = stream.readInt32()
            for i in range(nItems):
                path = stream.readInt32()
                row = []
                for j in range(path):
                    row.append(stream.readInt32())
                rows.append(row)

        for row in rows:
            it = tree.topLevelItem(row[0])
            for ix in row[1:]:
                it = it.child(ix)
            items.append(it)
        return items
Related Posts Related Posts :
  • Dynamically create variables in python
  • How to draw a curved line/arc in a polar plot with matplotlib?
  • GLib.idle_add(function) has different policies for different functions
  • Python: extract numbers based on letters
  • How to add Millions of contacts to telegram?
  • How can I structure my JSON schema to validate for DynamoDB and RESTAPI?
  • Seaborn Heatmap without lines between cells
  • How to connect functions to PyQt signals outside of main thread
  • How to unit test stream generators
  • Python finding hourly list of files from date
  • numpy.random to select a value from a given list that is itself selected at from a list
  • INSERT INTO .db does nothing. Why is it not working?
  • Bytes object stored in "repr format" as b'foo' instead of encode()-ing to string -- how to fix?
  • Tensorflow Sparse Tensors Issue
  • persistent Syntax Error in if statement inside for loop
  • Getting diagonal of a matrix in numpy and excluding an element
  • Spark SQL Partition By, Window, Order By, Count
  • vscode doesn't recognized my django module app. Warning from vscode
  • Get biggest coherent area
  • pkg_resources.DistributionNotFound: The 'pipenv==2018.10.13' distribution was not found and is required by the applicati
  • How to save image as binary compressed .tiff python?
  • Zapier Action Code: Python will not run with input_data variable
  • python-hypothesis: Retrieving or reformatting a falsifying example
  • How to Get All Results from Elasticsearch in Python
  • Replacing the elements in list at the positions given in replacement indices with new value in Python
  • Generating tuple from a list of items in Python
  • Python iterparse is skipping values
  • Add prefix to start of every line doesnt work
  • How to find last letter on word in string with find method?
  • Django Models - How do you add subtype choice when user selects choice?
  • Django : go back to correct paginator page
  • Webscraping: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop
  • Which distribution of python?
  • Save complete web page (incl css, images) using python/selenium
  • openpyxl conditonal formatting based on cell
  • Palindrome check with recursive function without slicing and loops
  • Delete class instance from memory
  • Sending GET request for an IP address
  • Change array values using lookup table
  • Pandas Dataframe groupby + agg + lambda + unique throwing a ValueError
  • Connect google cloud function to an oracle database
  • Cannot install es_core_news_sm from Spacy
  • loop through a single column in one dataframe compare to a column in another dataframe create new column in first datafr
  • How to perform a joint fit of several curves (in Python)?
  • How to change colorbar using Matplotlib?
  • Enumerating dataframe based on a column
  • Parsing a JSON using specific key words using Python
  • Create multiple functions to return separate dictionary results in 1 result box?
  • Extract substring from string using Python and regex
  • To concatenate a big dataframe from for loop outputs Python
  • Python3 error with str and byte code object
  • Trouble plotting histogram Bins are separated and the x-axis values are cramped
  • Pandas 'eval' with NaN
  • How to round a number to the specified upper or lower bond?
  • Python Pandas: setting the ylim value as the maximum value in my pivot table
  • How to get the latitude and longitude (map icon) from a website using selenium?
  • Scapy DNS Request
  • Pandas: repeat n times value of each n rows
  • Black background behind a figure's labels and ticks, only after saving figure but not in Python Interactive view (VS Cod
  • Python Regex: OR statement does not work in regex module
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org