python (pyqt) 表格显示图片的示例
调用接口激活显示数据所包含的图片:
停止调用接口几秒钟后表格填充固定图片显示为灰色:
代码:
#!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-import sys, os
import yaml
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import randomclass IconDelegate(QStyledItemDelegate):def initStyleOption(self, option, index):super(IconDelegate, self).initStyleOption(option, index)if option.features & QStyleOptionViewItem.HasDecoration:s = option.decorationSizes.setWidth(option.rect.width())option.decorationSize = sclass VisionDetectTable(QWidget):data_signal = pyqtSignal(list)Instance = None@classmethoddef ShowDetectData(cls, list):if cls.Instance:cls.Instance.data_signal.emit(list)def __init__(self, file_path=None):super(VisionDetectTable, self).__init__()self.columnCount = 3self.rowCount = 5self.count = 0self.detect = []# QWidget.__init__()self.file_path = sys.path[0] + "/vision_detect/"if file_path:self.file_path = file_pathself.loadyaml()self.initUI()self.data_signal.connect(self.setData)VisionDetectTable.Instance = selfself.freeze()self.timer_freeze = QTimer(self)self.timer_freeze_flag = 0self.timer_freeze.timeout.connect(self.freeze_check)self.timer_freeze.start(3000)# testself.timer = QTimer(self)self.timer.timeout.connect(self.showTest)self.timer.start(7000)def freeze_check(self):if self.timer_freeze_flag >= 0:self.timer_freeze_flag = self.timer_freeze_flag - 1if self.timer_freeze_flag == 0:self.freeze()passdef unfreeze(self):self.timer_freeze_flag = 2self.setEnabled(True)passdef freeze(self):self.detect = self.vision_detect_listself.showData()self.setEnabled(False)passdef loadyaml(self):p = os.path.abspath(self.file_path + "info.yaml") # 加载自动启动进程的配置文件f = open(p, 'r') # 当前python目录/filenamed = yaml.load(f)self.vision_detect_list = d["info"]self.vision_detect_list_obj = {
}# print self.vision_detect_list'''- id: 0label: keep_leftname: keep_leftnamecn: 靠左icon: traffic_sign_icon/keep_left.png- id: 1label: keep_rightname: keep_rightnamecn: 靠右icon: traffic_sign_icon/keep_right.png- id: 2label: limit_50name: limit_50namecn: 限速50icon: traffic_sign_icon/limit_50.png'''f.close()for i in self.vision_detect_list:self.vision_detect_list_obj[i["label"]] = iprinti["icon"]self.vision_detect_list_obj[i["label"]] = idef showTest(self):self.count = self.count + 1printself.countfakedata = []for i in self.vision_detect_list:if random.random() > 0.5:fakedata.append(i)# self.setData(fakedata)VisionDetectTable.ShowDetectData(fakedata)passdef setData(self, lst):self.unfreeze()self.detect = lstself.showData()passdef showData(self):l = len(self.detect)# self.table.clear()self.table.clearContents()mc = self.columnCount * self.rowCountempty = mc - lfor k in range(l):i = k / self.columnCountj = k % self.columnCountitem = self.detect[k]# self.table.clearCellWidget(i, j)tcw = self.tableCellWidget(item)self.table.setCellWidget(i, j, tcw)# print kif empty > 0:item = {
"label": "empty"}while l < mc:i = l / self.columnCountj = l % self.columnCount# item = self.detect[k]# self.table.clearCellWidget(i, j)tcw = self.tableCellWidget(item)self.table.setCellWidget(i, j, tcw)l = l + 1passdef tableCellWidget(self, item):nm = item["label"]widget = QWidget()score=""if "score" in item:score=str(item["score"])widget.setToolTip(nm+":"+score)hLayout = QVBoxLayout()hLayout.setContentsMargins(0, 0, 0, 0)widget.setLayout(hLayout)label = QLabel("")label.setAlignment(Qt.AlignCenter) # 水平居中if not nm in self.vision_detect_list_obj:nm="other_sign"#imgsrc = self.file_path + self.vision_detect_list_obj[nm]["icon"]label.setPixmap(QPixmap(imgsrc).scaled(50, 50)) # 只有图片# labeltxt = QLabel(r'0.5 ')# labeltxt.setAlignment(Qt.AlignCenter) # 水平居中hLayout.addWidget(label)# hLayout.addWidget(labeltxt)return widgetpassdef initUI(self):layout = QHBoxLayout()layout.setContentsMargins(0, 0, 0, 0)table = QTableWidget()table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive | QHeaderView.Stretch)# table.setGeometry(QRect(0, 0, self.geometry().width(), self.geometry().height() - 40))table.setColumnCount(self.columnCount)table.setRowCount(self.rowCount)# table.setEditTriggers(QAbstractItemView.NoEditTriggers)table.setSelectionMode(QAbstractItemView.NoSelection)table.setFocusPolicy(Qt.NoFocus)# for i in QAbstractItemView:printQAbstractItemViewself.setStyleSheet("QTableWidget::item:selected{ background-color: rgb(255,0,0);}") # 或#ffffffself.setStyleSheet("QTableWidget::item:focus{ background-color: rgb(0,255,255);}")# self.setStyleSheet("QTableView:item:selected {background-color: #FF9900; color: #0000FF}\n"# "QTableView:item:selected:focus {background-color: #ffff00; color: #FFffFF}")# table.setHorizontalHeaderLabels(['图片1', '图片2', '图片3'])table.verticalHeader().setVisible(False)table.horizontalHeader().setVisible(False)table.setDragEnabled(False)# table.setIconSize(QSize(50, 50))# delegate = IconDelegate(table)# table.setItemDelegate(delegate)for i in range(self.columnCount): # 让列宽和图片相同table.setColumnWidth(i, 100)for i in range(self.rowCount): # 让行高和图片相同table.setRowHeight(i, 80)layout.addWidget(table)self.setLayout(layout)self.table = table# self.table.setFixedSize(layout.sizeHint())def resizeEvent(self, e):self.table.resize(self.width(), self.height())# self.table.move(10, 20)if __name__ == '__main__':app = QApplication(sys.argv)layout = QVBoxLayout()layout.setContentsMargins(0, 0, 0, 0)widget = QWidget()widget.setLayout(layout)# widget.setStyleSheet('.QWidget{border-style:solid;border-width:3;margin:1px;padding:10px;border-color: red yellow blue green;}')widget.show()vdt = VisionDetectTable()# vdt.setContentsMargins(0, 0, 0, 0)layout.addWidget(vdt)# layout.addWidget(vdt,0,Qt.AlignCenter )# vdt.show()sys.exit(app.exec_())