我正试图通过用matplotlib imshow显示的numpy数组制作一个图标。
我成功地将颜色从matplotlib转换为尺寸为(n * n * 4)的numpy数组
然后我将此numpy数组转换为Qimage,然后转换为Qpixmap,以更新Qpushbutton的图标。
但是,按钮的图标未设置为我创建的图像。实际上,它什么也没做。如果我改用硬盘中的图像,则该图标已正确更新。
下面是代码示例:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import numpy as np
import sys
import matplotlib.pyplot as plt
class StimEdit(QMainWindow):
def __init__(self, parent=None):
super(StimEdit, self).__init__()
self.parent = parent
self.centralWidget = QWidget()
self.color = self.centralWidget.palette().color(QPalette.Background)
self.setCentralWidget(self.centralWidget)
self.mainHBOX_param_scene = QHBoxLayout()
self.B = QPushButton('')
self.B.setFixedSize(100,100)
self.B.clicked.connect(self.updateicon)
self.mainHBOX_param_scene.addWidget(self.B)
self.centralWidget.setLayout(self.mainHBOX_param_scene)
def updateicon(self):
CM = np.random.random((10,10))
ax = plt.imshow(CM)
colours = (ax.cmap(ax.norm( CM )) * 255).astype(np.uint8)
ncols, nrows, ncolors = colours.shape
# image = QImage(colours.tostring(),ncols, nrows, ncolors,QImage.Format_RGBA8888)
image = QImage(colours[:,:,:3].tostring(),ncols, nrows, ncolors-1,QImage.Format_RGB888)
rMyIcon = QPixmap(image)
self.B.setIcon(QIcon(rMyIcon))
self.B.setIconSize(QSize(100, 100))
self.parent.processEvents()
def main():
app = QApplication(sys.argv)
ex = StimEdit(app)
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()