I'm trying to make an icon from a numpy array displayed with matplotlib imshow.
I succeed in getting colors from matplotlib into a numpy array of dimension (n*n*4)
I then convert this numpy array to an Qimage then into a Qpixmap in order to update the Icon of a Qpushbutton.
However the icon of the button is not set to the image I created. In fact it doesn't do anything. If I used an image from my hard-drive instead, the icon is correctly updated.
Here a sample of code :
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()