由于QListWidget自带滚动条,所以可以用QListWidget做一个纯图片列表或者做一个文字(含图标)列表
1.简单粗暴一点的:
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QListWidget, QLineEdit, \
QPushButton, QListWidgetItem, QLabel
from PySide6.QtGui import QPixmap
from PySide6.QtCore import QByteArray
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 初始化UI界面
self.search_line_edit = QLineEdit()
self.search_button = QPushButton('搜索')
self.list_widget = QListWidget()
self.hbox = QHBoxLayout()
self.vbox = QVBoxLayout()
self.init_ui()
self.search_images()
def init_ui(self):
# 将搜索框和搜索按钮添加到水平布局中
self.hbox.addWidget(self.search_line_edit)
self.hbox.addWidget(self.search_button)
# 将水平布局和QListWidget添加到垂直布局中
self.vbox.addLayout(self.hbox)
self.vbox.addWidget(self.list_widget)
# 将垂直布局添加到主窗口中
widget = QWidget()
widget.setLayout(self.vbox)
self.setCentralWidget(widget)
# 设置窗口属性
self.setWindowTitle('ListWidget_Pixmap')
def search_images(self):
images = ['jiantou.png']
for image in images:
byte_array = QByteArray(image)
label = QLabel()
item = QListWidgetItem()
pixmap = QPixmap(image).scaled(100, 100)
label.setPixmap(pixmap)
pixmap.loadFromData(byte_array)
item.setSizeHint(label.sizeHint())
self.list_widget.addItem(item)
self.list_widget.setItemWidget(item, label)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
2.图标和文字的:
# 剩下的自己加进去
def add_images_to_list(self):
# 添加图片到列表中
for i in range(50):
image = QImage('jiantou.png'.format(i))
pixmap = QPixmap(image).scaledToWidth(100)
item = QListWidgetItem(QIcon(pixmap), 'Image {}'.format(i))
self.list_widget.addItem(item)
3.高级一点的:
import os
from PySide6 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.list_widget = QtWidgets.QListWidget(self)
self.setCentralWidget(self.list_widget)
# 循环添加图片到QListWidget中
for file_name in os.listdir(r'./images/images'):
if not file_name.endswith('.png'):
continue
item = QtWidgets.QListWidgetItem(file_name)
# 加载图片并转换为QPixmap
image_path = os.path.join('images', file_name)
pixmap = QtGui.QPixmap(image_path)
# 设置ListWidgetItem的图标
item.setIcon(QtGui.QIcon(pixmap))
self.list_widget.addItem(item)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec()
这是三种在QListWidget中添加图片的方式
版权声明:本文为qq_63392990原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。