Home  >  Article  >  Backend Development  >  python3+PyQt5 implements drag and drop function

python3+PyQt5 implements drag and drop function

不言
不言Original
2018-04-24 11:46:453340browse

This article mainly introduces the drag-and-drop function of python3 PyQt5 to everyone in detail. It has certain reference value. Interested friends can refer to it.

This article is a review of "Python Qt GUI Rapid Programming" The drag-and-drop example in Chapter 10 is rewritten in Python3 PyQt5, and the chart list, table, etc. are dragged and dropped to each other. The basic principles are the same, and setAcceptDrops(True) and setDragEnabled(True) are used.

#!/usr/bin/env python3
import os
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QDialog, QHBoxLayout,
  QListWidget, QListWidgetItem, QSplitter, QTableWidget)
from PyQt5.QtGui import QIcon

class Form(QDialog):

 def __init__(self, parent=None):
  super(Form, self).__init__(parent)

  listWidget = QListWidget()
  listWidget.setAcceptDrops(True)
  listWidget.setDragEnabled(True)

  path = os.path.dirname(__file__)
  for image in sorted(os.listdir(os.path.join(path, "images"))):
   if image.endswith(".png"):
    item = QListWidgetItem(image.split(".")[0].capitalize())
    item.setIcon(QIcon(os.path.join(path,
         "images/{0}".format(image))))
    listWidget.addItem(item)
  iconListWidget = QListWidget()
  iconListWidget.setAcceptDrops(True)
  iconListWidget.setDragEnabled(True)
  iconListWidget.setViewMode(QListWidget.IconMode)     

  tableWidget = QTableWidget()
  tableWidget.setRowCount(5)
  tableWidget.setColumnCount(2)
  tableWidget.setHorizontalHeaderLabels(["Column #1", "Column #2"])
  tableWidget.setAcceptDrops(True)
  tableWidget.setDragEnabled(True)

  splitter = QSplitter(Qt.Horizontal)
  splitter.addWidget(listWidget)
  splitter.addWidget(iconListWidget)
  splitter.addWidget(tableWidget)
  layout = QHBoxLayout()
  layout.addWidget(splitter)
  self.setLayout(layout)

  self.setWindowTitle("Drag and Drop")

if __name__ == "__main__":
 app = QApplication(sys.argv)
 form = Form()
 form.show()
 app.exec_()

Running results:

##Related recommendations:


python3 Detailed explanation of PyQt5 custom view

python3 PyQt5 implements histogram

python3 PyQt5 implements document printing function

The above is the detailed content of python3+PyQt5 implements drag and drop function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn