【问题标题】:How to make Qicon fill entire QTableWidgetItem or grid in QTableWidget [duplicate]如何使Qicon填充QTableWidget中的整个QTableWidgetItem或网格[重复]
【发布时间】:2021-06-09 12:19:36
【问题描述】:

我在 QTableWidget 上工作过,问题是如何制作一个 Qicon 来填充整个网格或 QtableWidget 中的 QTableWidget,甚至拉伸网格的宽度或高度,谢谢。

代码如下:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon

class Table(QWidget):
    def __init__(self):
        super(Table, self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("QTableWidget Example")
        self.resize(400,300)
        self.layout=QHBoxLayout()
        self.TableWidget=QTableWidget(2,3)

        self.TableWidget.setHorizontalHeaderLabels(['Nmae','Sex','Weight(kG)'])

        self.newItem=QLineEdit('Jack')        
        self.TableWidget.setCellWidget(0,0,self.newItem)        

        self.newItem=QLineEdit('Male')        
        self.TableWidget.setCellWidget(0,1,self.newItem)        
        self.newItem=QLineEdit('160')        
        self.TableWidget.setCellWidget(0,2,self.newItem)     

        self.newItem=QTableWidgetItem(QIcon("./icon/1.png"),'')
        self.TableWidget.setItem(1,0,self.newItem) 

        self.newItem=QTableWidgetItem(QIcon("./icon/2.png"),'')
        self.TableWidget.setItem(1,1,self.newItem)

        self.newItem=QTableWidgetItem(QIcon("./icon/2.png"),'')
        self.TableWidget.setItem(1,2,self.newItem)
   

        self.layout.addWidget(self.TableWidget)

        self.setLayout(self.layout)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    win=Table()
    win.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 我看到您正在为所有列设置标题标签,但随后您也在为标题设置项目:结果是这些列的标签将被覆盖(或者,更好的是,清除)。您是打算只显示拉伸图像,还是还想显示其上方的部分文本?另外,无论如何,您的问题有点困惑:您是要拉伸图标以填充该部分还是整个标题?
  • 抱歉造成混淆,我的目的是拉伸图像/图标以填充整个部分而不是标题,现在我修改了代码,请帮助再次检查,谢谢。
  • 这些实际图像是否具有某些特定内容,或者您​​是否尝试绘制填充整个单元格的颜色?
  • 是的,这些图像旨在将整个单元格填充为三种类型,包括用绿色填充整个单元格,用绿色填充前半部分,用绿色填充后半部分,我认为无法通过填充完成此任务单元格,所以我为每个目的画了 3 张不同的图片
  • 我投票决定重新打开,因为 OP 还需要拉伸图像,而重复的答案将导致保持图像的原始纵横比。

标签: python pyqt pyqt5 qtablewidget


【解决方案1】:

您需要使用item delegate,然后检查索引是否具有装饰角色的有效数据,在这种情况下,绘制它而不是使用默认的绘画功能。

class ImageDelegate(QStyledItemDelegate):
    def paint(self, painter, opt, index):
        decoration = index.data(Qt.DecorationRole)
        if decoration is not None:
            if isinstance(decoration, QIcon):
                decoration = decoration.pixmap(opt.rect.size())
            # decoration role can also contain a QColor, we only want a pixmap
            if isinstance(decoration, QPixmap):
                painter.drawPixmap(opt.rect, decoration)
                return
        super().paint(painter, opt, index)


class Table(QWidget):
    # ...
    def initUI(self):
        # ...
        self.delegate = ImageDelegate(self.TableWidget)
        self.TableWidget.setItemDelegate(self.delegate)

【讨论】:

  • 这正是我需要的,非常感谢
猜你喜欢
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多