PyQT5之QListView
实例1:
from PyQt5.QtWidgets import QMessageBox, QListView, QStatusBar, QMenuBar, QMenu, QAction, QLineEdit, QStyle, QFormLayout, QVBoxLayout,QWidget,QApplication ,QHBoxLayout, QPushButton,QMainWindow,QGridLayout,QLabel
from PyQt5.QtGui import QIcon, QPixmap, QStandardItem, QStandardItemModel
from PyQt5.QtCore import QStringListModel, QAbstractListModel, QModelIndex, QSize
import sys
class WindowClass(QMainWindow):
def __init__(self, parent=None):
super(WindowClass, self).__init__(parent)
self.layout = QVBoxLayout()
self.resize(200, 300)
listModel = QStringListModel()
listView = QListView()
items = ["张三", "李四", "小明", "JONES"]
listModel.setStringList(items)
listView.setModel(listModel)
listView.clicked.connect(self.checkItem)
self.layout.addWidget(listView)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
def checkItem(self, index):
QMessageBox.information(self, "ListView", "选择项是:%d"%(index.row()))
if __name__ == "__main__":
app = QApplication(sys.argv)
win = WindowClass()
win.show()
sys.exit(app.exec_())
实例2:
# QListView使用
from PyQt5.QtWidgets import QMessageBox,QListView, QStatusBar, QMenuBar,QMenu,QAction,QLineEdit,QStyle,QFormLayout, QVBoxLayout,QWidget,QApplication ,QHBoxLayout, QPushButton,QMainWindow,QGridLayout,QLabel
from PyQt5.QtGui import QIcon,QPixmap,QStandardItem,QStandardItemModel
from PyQt5.QtCore import QStringListModel,QAbstractListModel,QModelIndex,QSize
import sys
class WindowClass(QMainWindow):
def __init__(self, parent=None):
super(WindowClass, self).__init__(parent)
self.layout = QVBoxLayout()
self.resize(200, 300)
listView = QListView()
listView.setViewMode(QListView.ListMode)#或者使用QListView.IconMode QListView.ListMode
# listView.setMovement(QListView.Static)
listView.setIconSize(QSize(20,20)) # 图标的大小(原始图标大小如果100,100,此时设置草果原始大小则失效)
listView.setGridSize(QSize(60,40))#每个选项所在网格大小(每个选项外层grid宽高)
listView.setMaximumHeight(200)#listView整体最大高度
# listView.setMinimumSize(QSize(200,200))#listView最小面积(一般如果设置最大高和宽属性后就不设置这个属性了)
# listView.setMaximumSize(QSize(500,500))#listVIew最大面积(一般如果设置最大高和宽属性后就不设置这个属性了)
listView.setMinimumHeight(120)#listView最小高度
listView.setResizeMode(QListView.Adjust)
#listView.setMovement(QListView.Static)#设置图标可不可以移动,默认是可移动的,但可以改成静态的:
self.item_1 = QStandardItem(QIcon("./image/save.ico"), "普通员工A");
self.item_2 = QStandardItem(QIcon("./image/save.ico"), "普通员工B");
model = QStandardItemModel()
model.appendRow(self.item_1)
model.appendRow(self.item_2)
listView.setModel(model)
listView.clicked.connect(self.checkItem)
self.layout.addWidget(listView)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
def checkItem(self, index):
QMessageBox.information(self, "ListView", "选择项是:%d"%(index.row()))
if __name__=="__main__":
app = QApplication(sys.argv)
win = WindowClass()
win.show()
sys.exit(app.exec_())