In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use mimeData to achieve drag events in PyQt5". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Realization idea
1. A brief introduction to QMimeData
2. Use case 1 of QMimeData: drag and drop external files and display them in QT
3. Use case 2 of QMimeData: item exchange between two QListWidget
1. A brief introduction to QMimeData
Some of the relationship between drag and drop events and QMimeData has been explained clearly in the first article. The main purpose of this article is to store some data in QMimeData for judgment when dragging and placing (and data is transmitted through QMimeData).
In the first example: because the drag and drop of the file itself stores some information, we do not create a QDrag and a QMimeData as we did in the first article
In the second example: we set a text value for mimeData at this time to exchange ItemList later
2. Use case 1 of QMimeData implements dragging external files in QT and displays #-*-coding: utf-8-*-import sysfrom PyQt5.QtWidgets import QApplication, QMainWindow, QTextEditfrom PyQt5.QtCore import QIODevice, QFileclass ComplexDrag (QMainWindow): def _ init__ (self): super (ComplexDrag) Self). _ init__ () self.setAcceptDrops (True) self.textEditor = None self.initUI () def initUI (self): self.textEditor = QTextEdit () self.setCentralWidget (self.textEditor) self.textEditor.setAcceptDrops (False) self.setAcceptDrops (True) self.setWindowTitle ("drag") def dragEnterEvent (self) Event): if event.mimeData () .hasFormat ("text/uri-list"): # the difference between this function and accept is shown below as event.acceptProposedAction () def dropEvent (self) Event): urls = event.mimeData () .urls () if urls = "": return fileName = urls.pop () .toLocalFile () if fileName = = "": return if self.readFile (fileName): self.setWindowTitle ("Drag File Success") def readFile (self FileName): r = False file = QFile (fileName) content = "" if file.open (QIODevice.ReadOnly): content = file.readAll () r = True self.textEditor.setText (str (content) "utf-8") return rif _ _ name__ = ='_ main__': app = QApplication (sys.argv) ex = ComplexDrag () ex.show () app.exec_ ()
The above code can drag external files in and display them, and there are a few key points to note:
1. We did not create a QDrag event, because the start of the drag and drop is not in the window and the Widget within the window, but directly from the outside. Such events already have QDrag.
2. We use the information carried in QMimeData to determine whether the incoming drag event is what we need, that is, event.mimeData (). HasFormat ("text/uri-list"). For the type in it, you can find the website Media Types on your own.
3. The above reasons why we use acceptProposedAction instead of event.accept are as follows
4. After dragging and dropping, we read the file in and display it.
3. QMimeData use case 2 item exchange between two QListWidget #-*-coding: utf-8-*-import sysfrom threading import Eventfrom PyQt5.QtGui import QDrag, QPixmapfrom PyQt5.QtWidgets import QApplication, QHBoxLayout, QListWidget, QDialogfrom PyQt5.QtCore import QMimeData, Qtclass MainWindow (QDialog): def _ init__ (self): super (MainWindow) Self). _ init__ () self.projectA = ComplexDrag (self) self.projectB = ComplexDrag (self) self.projectA.addItem ("Giosue Carducci") self.projectA.addItem ("Eyvind Johnson") self.projectA.addItem ("Sally Prudhomme") self.projectA.addItem ("Henryk Sienkiewicz") self.projectA.addItem ("Carl Spitteler") self.projectA.addItem (" Rabindranath Tagore ") self.projectA.addItem (" Kawabata Yasunari ") self.projectB.addItem (" Rudolf Eucken ") self.projectB.addItem (" Anatole France ") self.projectB.addItem (" Rudyard Kipling ") self.projectB.addItem (" Thomas Mann ") self.projectB.addItem (" Eugene O'Neill ") self.projectB.addItem (" Sigrid Undset ") lay = QHBoxLayout () Lay.addWidget (self.projectA) lay.addWidget (self.projectB) self.setLayout (lay) class ComplexDrag (QListWidget): onDropEvent = Event () def _ init__ (self Parent=None): super (ComplexDrag, self). _ init__ (parent) self.setAcceptDrops (True) self.startPos = None def removeSel (self): listItems = self.selectedItems () if not listItems: return for item in listItems: self.takeItem (self.row (item)) def mousePressEvent (self Event): if event.button () = Qt.LeftButton: self.startPos = event.pos () super (ComplexDrag, self) .mousePressEvent (event) def mouseMoveEvent (self Event): distance = (event.pos ()-self.startPos). ManhattanLength () if distance > = QApplication.startDragDistance (): item = self.currentItem () if item: mimeData = QMimeData () mimeData.setText (item.text ()) drag = QDrag (self) drag.setMimeData (mimeData) Pixmap = QPixmap ("computer.svg") .scaled 20, Qt.KeepAspectRatio) drag.setPixmap (pixmap) self.removeItemWidget (item) if drag.exec (Qt.MoveAction) = = Qt.MoveAction: self.removeSel () super (ComplexDrag, self) .mouseMoveEvent (event) def dragMoveEvent (self) Event): source = event.source () if source and source! = self: event.setDropAction (Qt.MoveAction) def dragEnterEvent (self, event): source = event.source () if source and source! = self: event.setDropAction (Qt.MoveAction) event.accept () def dropEvent (self Event): source = event.source () if source and source! = self: self.addItem (event.mimeData (). Text () event.setDropAction (Qt.MoveAction) if _ _ name__ ='_ main__': app = QApplication (sys.argv) ex = MainWindow () ex.show () app.exec_ ()
Briefly describe the above implementation process:
1. We put two QListWidget in one QWidget and implement the exchange of item between QListWidget.
2. QDrag is created in mouseMoveEvent in QListWidget, and we create a QMimeData and store the text of the currently selected item in it. Here we also set the icon style when dragging (the above gif is not resized, so you can take the code and run it yourself)
3. Determine whether it is a homologous event in dragMoveEvent, and set the current drag and drop to Qt.MoveAction if it is not of the same origin.
4. Receive qualified drag events in dragEnterEvent
5. In dropEvent, get the originally set text value from QMimeData and add it to the current QListWidget. Note that the self here is not the self of the original QDrag signal. Here, the two self actually represent two windows.
6. The exec method is a blocking method, so after the whole drag-and-drop event is run, we will go back to the following code and finish executing the later method. At this point, we delete the item that we dragged.
If drag.exec (Qt.MoveAction) = = Qt.MoveAction: self.removeSel () "how PyQt5 uses mimeData to implement drag events" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.