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堆排序原理与实现方法详解

Python堆排序原理与实现方法详解

本文实例讲述了Python堆排序原理与实现方法。分享给大家供大家参考,具体如下: 在这里要事先说明一下我也是新手,很多东西我了解不是很深入,写算法完全是锻炼自己逻辑能力同时顺带帮助读研的...

Python中请不要再用re.compile了

Python中请不要再用re.compile了

前言 如果大家在网上搜索Python 正则表达式,你将会看到大量的垃圾文章会这样写代码: import re pattern = re.compile('正则表达式') text...

python多线程使用方法实例详解

本文实例讲述了python多线程使用方法。分享给大家供大家参考,具体如下: threading 模块支持守护线程, 其工作方式是:守护线程一般是一个等待客户端请求服务的服务器。 如果把一...

Python探索之pLSA实现代码

pLSA(probabilistic Latent Semantic Analysis),概率潜在语义分析模型,是1999年Hoffman提出的一个被称为第一个能解决一词多义问题的模型,...

图解python全局变量与局部变量相关知识

图解python全局变量与局部变量相关知识

这篇文章主要介绍了图解python全局变量与局部变量相关知识,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 了解全局变量和局部变量之前...