Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 990577
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T05:57:56+00:00 2026-05-16T05:57:56+00:00

i can’t find an example on dragging (and dropping) multiple elements with Qt/PyQt; In

  • 0

i can’t find an example on dragging (and dropping) multiple elements with Qt/PyQt;
In my case i need to drag elements from this QTableView:

class DragTable(QTableView):
    def __init__(self, parent = None):
        super(DragTable, self).__init__(parent)
        self.setDragEnabled(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat("application/pubmedrecord"):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, event):
        print type(event)
        index = self.indexAt(event.pos())
        if not index.isValid():
            return

        selected = index.row()
        bstream = cPickle.dumps(selected)
        mimeData = QMimeData()
        mimeData.setData("application/pubmedrecord", bstream)
        drag = QDrag(self)
        drag.setMimeData(mimeData)
        pixmap = QPixmap(":/drag.png")

        drag.setHotSpot(QPoint(pixmap.width()/3, pixmap.height()/3))
        drag.setPixmap(pixmap)
        result = drag.start(Qt.MoveAction)

    def mouseMoveEvent(self, event):
        self.startDrag(event)

To this QLabel (My dropzone):

class TagLabel(QLabel):
    def __init__(self, text, color, parent = None):
        super(TagLabel, self).__init__(parent)
        self.tagColor = color
        self.setText(text)
        self.setStyleSheet("QLabel { background-color: %s; font-size: 14pt; }" % self.tagColor)
        self.defaultStyle = self.styleSheet()
        self.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat("application/pubmedrecord"):
            self.set_bg(True)
            event.accept()
        else:
            event.reject()

    def dragLeaveEvent(self, event):
        self.set_bg(False)
        event.accept()

    def dropEvent(self, event):
        self.set_bg(False)
        data = event.mimeData()
        bstream = data.retrieveData("application/pubmedrecord", QVariant.ByteArray)
        selected = pickle.loads(bstream.toByteArray())
        event.accept()
        self.emit(SIGNAL("dropAccepted(PyQt_PyObject)"), (selected, str(self.text()), str(self.tagColor)))

    def set_bg(self, active = False):
        if active:
            style = "QLabel {background: yellow; font-size: 14pt;}"
            self.setStyleSheet(style)
        else:
            self.setStyleSheet(self.defaultStyle)

Any tips? Thank you!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T05:57:57+00:00Added an answer on May 16, 2026 at 5:57 am

    Here’s a full working example:

    from PyQt4 import QtCore, QtGui, Qt
    import cPickle
    import pickle
    

    Why are you using cPickle as well as pickle?

    class DragTable(QtGui.QTableView):
        def __init__(self, parent = None):
            super(DragTable, self).__init__(parent)
            self.setDragEnabled(True)
            self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
    

    You probably want to set the selection behavior here, because I’m assuming row-based data presentation. You may of course change that.

        def dragEnterEvent(self, event):
            if event.mimeData().hasFormat("application/pubmedrecord"):
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
    
        def startDrag(self, event):
    

    Your code assumes only one index here, based on the event position. For a QTableView, this is unnecessary, as it already handles the mouse click itself. Instead, it’s better to depend on Qt to provide you with the information that you actually need, as always. Here, I’ve chose to use selectedIndexes().

            indices = self.selectedIndexes()
    

    Indices is now a list of QModelIndex instances, that I chose to convert to a set of row numbers. It’s also possible to convert these to a list of QPersistentModelIndexes, depending on your needs.

    One thing that may surprise you here, is that indices contains indexes for all cells in the table, not all rows, regardless of the selection behavior. That’s why I chose to use a set instead of a list.

            selected = set()
            for index in indices:
                selected.add(index.row())
    

    I left the rest untouched, assuming that you know what you’re doing there.

            bstream = cPickle.dumps(selected)
            mimeData = QtCore.QMimeData()
            mimeData.setData("application/pubmedrecord", bstream)
            drag = QtGui.QDrag(self)
            drag.setMimeData(mimeData)
            pixmap = QtGui.QPixmap(":/drag.png")
    
            drag.setHotSpot(QtCore.QPoint(pixmap.width()/3, pixmap.height()/3))
            drag.setPixmap(pixmap)
            result = drag.start(QtCore.Qt.MoveAction)
    
        def mouseMoveEvent(self, event):
            self.startDrag(event)
    
    
    class TagLabel(QtGui.QLabel):
        def __init__(self, text, color, parent = None):
            super(TagLabel, self).__init__(parent)
            self.tagColor = color
            self.setText(text)
            self.setStyleSheet("QLabel { background-color: %s; font-size: 14pt; }" % self.tagColor)
            self.defaultStyle = self.styleSheet()
            self.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
            self.setAcceptDrops(True)
    
        def dragEnterEvent(self, event):
            if event.mimeData().hasFormat("application/pubmedrecord"):
                self.set_bg(True)
                event.accept()
            else:
                event.reject()
    
        def dragLeaveEvent(self, event):
            self.set_bg(False)
            event.accept()
    
        def dropEvent(self, event):
            self.set_bg(False)
            data = event.mimeData()
            bstream = data.retrieveData("application/pubmedrecord", QtCore.QVariant.ByteArray)
            selected = pickle.loads(bstream.toByteArray())
            event.accept()
            self.emit(QtCore.SIGNAL("dropAccepted(PyQt_PyObject)"), (selected, str(self.text()), str(self.tagColor)))
    

    Unless you are interfacing with C++-code with this signal, it’s not necessary to add a signal argument here, you may also use dropAccepted without parentheses and PyQt4 will do the right thing.

        def set_bg(self, active = False):
            if active:
                style = "QLabel {background: yellow; font-size: 14pt;}"
                self.setStyleSheet(style)
            else:
                self.setStyleSheet(self.defaultStyle)
    
    
    
    app = QtGui.QApplication([])
    
    l = TagLabel("bla bla bla bla bla bla bla", "red")
    l.show()
    
    m = QtGui.QStandardItemModel()
    for _ in xrange(4):
        m.appendRow([QtGui.QStandardItem(x) for x in ["aap", "noot", "mies"]])
    
    t = DragTable()
    t.setModel(m)
    t.show()
    
    def h(o):
        print "signal handled", o
    l.connect(l, QtCore.SIGNAL("dropAccepted(PyQt_PyObject)"), h)
    
    app.exec_()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 502k
  • Answers 502k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer See: Browser support for CSS3 and HTML5 When can I… May 16, 2026 at 2:34 pm
  • Editorial Team
    Editorial Team added an answer reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]])) May 16, 2026 at 2:34 pm
  • Editorial Team
    Editorial Team added an answer This page should explain the encoding algorithm: https://web.archive.org/web/20100830111303/https://www.swetake.com/qr/qr1_en.html May 16, 2026 at 2:34 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Does anyone know how can I replace this 2 symbol below from the string
Can I use the following across all browsers? <a href=# onclick=doSomething()>Click here.</a> Is this
Can anyone tell me what's wrong with this robots.txt? http://bizup.cloudapp.net/robots.txt The following is the
Can anyone pls let me know the exact c++ code of case sensitive comparison
Can I invoke an option on a COM Add-in from a VBA macro in
I have a jquery bug and I've been looking for hours now, I can't
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have text I am displaying in SIlverlight that is coming from a CMS
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) I have a Rails
Can anyone kindly explain how to send a concatenated WAP PUSH SMS? I can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.