python3+PyQt5实现拖放功能

yipeiwu_com6年前Python基础

本文是对《Python Qt GUI快速编程》的第10章的例子拖放用Python3+PyQt5进行改写,对图表列表,表格等进行相互拖放,基本原理雷同,均采用setAcceptDrops(True)和setDragEnabled(True)。

#!/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_()

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 通过URL打开图片实例详解

Python 通过URL打开图片实例详解 不论是用OpenCV还是PIL,skimage等库,在之前做图像处理的时候,几乎都是读取本地的图片。最近尝试爬虫爬取图片,在保存之前,我希望能先...

Python Trie树实现字典排序

Python Trie树实现字典排序

一般语言都提供了按字典排序的API,比如跟微信公众平台对接时就需要用到字典排序。按字典排序有很多种算法,最容易想到的就是字符串搜索的方式,但这种方式实现起来很麻烦,性能也不太好。Trie...

wxPython电子表格功能wx.grid实例教程

本文实例为大家分享了wxPython电子表格功能的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python #encoding: utf8 import wx...

Python小程序 控制鼠标循环点击代码实例

这篇文章主要介绍了Python小程序 控制鼠标循环点击代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 from ctype...

python的多重继承的理解

python的多重继承的理解

python的多重继承的理解 Python和C++一样,支持多继承。概念虽然容易,但是困难的工作是如果子类调用一个自身没有定义的属性,它是按照何种顺序去到父类寻找呢,尤其是众多父类中有多...