ui转py文件:
listviewdemo.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'listviewdemo.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(895, 611) self.listViewtest = QtWidgets.QListView(Form) self.listViewtest.setGeometry(QtCore.QRect(210, 190, 256, 192)) self.listViewtest.setObjectName("listViewtest") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form"))
主程序:
# -*- coding: utf-8 -*- import os, sys from PyQt5.Qt import * from debugwm.listviewdemo import Ui_Form #使用QStringListModel作为QListView的Model. QStringListModel提供了所有可编辑模型的标准函数,将字符串列表中的数据存储为一个一列多行的模型。换个说法,符号串的列表无法直接传入QListView对象和QComboBox,需要QStringListModel做为中间传递过程。 class ListViewPane(QWidget, Ui_Form): def __init__(self, parent=None, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.setupUi(self) #垂直布局 layout = QVBoxLayout() slm = QStringListModel() # 创建mode self.qList = ['data1', 'data2', 'data3', 'data4'] # 添加的数组数据 slm.setStringList(self.qList) # 将数据设置到model self.listViewtest.setModel(slm) ##绑定 listView 和 model #按下任意键编辑或双击编辑 self.listViewtest.setEditTriggers(QAbstractItemView.AnyKeyPressed | QAbstractItemView.DoubleClicked) self.listViewtest.clicked.connect(self.clickedlist) # listview 的点击事件 layout.addWidget(self.listViewtest) # 将list view添加到layout self.setLayout(layout) # 将lay 添加到窗口 def clickedlist(self, qModelIndex): QMessageBox.information(self, "QListView", "你选择了: " + self.qList[qModelIndex.row()]) print("点击的是:" + str(qModelIndex.row())) if __name__ == "__main__": if __name__ == '__main__': import sys app = QApplication(sys.argv) # 创建一个widget组件基础类 startpane = ListViewPane() startpane.show() # 循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过 sys.exit(app.exec_())