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 执行shell命令并将结果保存的实例

方法1: 将shell执行的结果保存到字符串 def run_cmd(cmd): result_str='' process = subprocess.Popen(cmd, sh...

python实现简单socket程序在两台电脑之间传输消息的方法

本文实例讲述了python实现简单socket程序在两台电脑之间传输消息的方法。分享给大家供大家参考。具体分析如下: python开发简单socket程序在两台电脑之间传输消息,分为客户...

python模块之sys模块和序列化模块(实例讲解)

python模块之sys模块和序列化模块(实例讲解)

sys模块 sys模块是与python解释器交互的一个接口 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit...

Pandas 数据框增、删、改、查、去重、抽样基本操作方法

总括 pandas的索引函数主要有三种: loc 标签索引,行和列的名称 iloc 整型索引(绝对位置索引),绝对意义上的几行几列,起始索引为0 ix 是 iloc 和 loc的合体 a...

python leetcode 字符串相乘实例详解

给定两个以字符串形式表示的非负整数 num1 和  num2 ,返回  num1 和  num2 的乘积,它们的乘积也表示为字符串形式。 示例 1: 输入:...