python - 在 PyQt 中自定义 MPL

标签 python matplotlib pyqt5

所以我一直在对 PyQt 和 MPL 进行大量研究,但我仍然遇到一些无法解决的问题。

第一个是这个:如何更改FigureCanvas背景颜色(它是 this image 中的灰色部分)。 FigureCanvas 没有脸部颜色或背景颜色或我能想到或找到的任何其他属性。我可以改变轴、绘图上的颜色(这就是我得到你可以看到的黑色背景的方式),但不能改变 Canvas 本身。

第二个问题:如何摆脱在十字准线顶部仍然可见的鼠标指针?或者更好的是,当光标进入 mpl FigureCanvas 小部件时更改光标(因此在离开时再次返回)。

编辑:这是我根据要求编写的一些代码。我通过以下方式从 Qt 调用 MPL 数据。

我的主窗口:

from PyQt5.QtCore import pyqtSlot as Slot
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic

# MPL class
from pyqt5_mpl import mpl_figure

# Select Qt5 user interface.
qtCreatorFile = '<local filepath>'
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class main(QtWidgets.QMainWindow, Ui_MainWindow):

    def __init__(self):
        # Inititate UI.
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        # Create data structures.
        global a
        a = a_dataclass()

        # Create MPL Canvases (Layout->CreateMPLCanvas->AddWidget).
        # Create class instances for each figure.
        a.im1 = mpl_figure()
        a.im2 = mpl_figure()

        # Create Layouts and add widgets.
        a_layout = QtWidgets.QHBoxLayout(self.tab1)
        a_layout.addWidget(a.im1.canvas)
        a_layout.addWidget(a.im2.canvas)

        # Load images.
        a.im1.loadimage('image file path',a.pix)
        a.im2.loadimage('image file path',a.pix)
        # a.pix is dimensions for extent in plot.

if __name__ == "__main__":
    # QApp 
    app = QtWidgets.QApplication(sys.argv)
    # QWidget (MainWindow)
    window = main()
    window.show()
    sys.exit(app.exec_())

我的 mpl_figure 类:

import matplotlib as mpl
mpl.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

class mpl_figure:

    def __init__(self):
        # Set up empty plot variables.
        self.image = None
        # Create a figure to plot on.
        fig = plt.figure()
        fig.set_facecolor('black') # This does nothing...
        # Create an axis in the figure.
        self.ax = fig.add_subplot(111, axisbg='black')
        # Create a canvas widget for Qt to use.
        self.canvas = FigureCanvas(fig)
        # Create cursor widget.
        self.cursor = mpl.widgets.Cursor(self.ax)
        # Refresh the canvas.
        self.canvas.draw()

    def loadimage(self,fn,pix):
        # Read in image.
        self.data = plt.imread(fn)
        # Calculate the extent.
        self.dims = np.array([0, pix[0]*np.shape(self.data)[1],0,pix[1]*np.shape(self.data)[0]])
        # Display the image.
        self.image = self.ax.imshow(self.data, cmap='gray', extent=self.dims)
        self.ax.set_autoscale_on(False)
        # Refresh the canvas.
        self.canvas.draw()
        # Start Callback ID
        self.cid = self.canvas.mpl_connect('button_press_event', self.onclick)

    def onclick(self,event):
        # Do stuff...
        pass

我尝试对 self.canvas 或Fig 进行更改的所有尝试。就其样式而言,它被渲染为静音,并且什么也不做。至于当您输入 mpl_widget 时更改光标(或隐藏它,它是指针),我只是不确定如何执行此操作。我记得在 mpl 中看到了一些与连接“event_leave_figure”有关的东西,但无法在它和 PyQt 之间建立联系<-这是重要的一点。有什么想法吗?

最佳答案

感谢您提供MINIMAL WORKING example以及在提问之前进行谷歌搜索。这总是可以节省很多时间。

因此以下代码会生成如下所示的图像。

import sys
from PyQt4 import QtGui, QtCore
import matplotlib 
import numpy as np
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.main_widget = QtGui.QWidget(self)
        self.setCentralWidget(self.main_widget)
        l = QtGui.QVBoxLayout(self.main_widget)

        self.fig = Figure(figsize=(5,3), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        l.addWidget(self.canvas)

        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2*np.pi*t)*np.exp(-t/7/np.pi)
        self.ax.plot(t, s, color="#0095a2", lw=3)

        #set some alpha
        self.fig.patch.set_alpha(0.5)
        #set color
        self.fig.patch.set_facecolor('#cd0e49')

        self.cursor = matplotlib.widgets.Cursor(self.ax)
        #set cursor
        #self.canvas.setCursor(QtGui.QCursor(QtCore.Qt.BlankCursor))
        #since I find Blank cursor very confusing, I will use a better one:
        self.canvas.setCursor(QtGui.QCursor(    QtCore.Qt.SizeAllCursor))



qApp = QtGui.QApplication(sys.argv)

aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())

enter image description here

关于python - 在 PyQt 中自定义 MPL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786721/

相关文章:

python - 如何在 Windows 7 上安装 SIP 和 PyQT

python - 将 x 轴绘制为日期

python - 关于 matplotlib 的 .show()

python - 在 python 中运行时将数据从 GUI 传递到线程

python - QFileDialog - PyQt4/PyQt5/PySide 之间的区别

python - Django 将用户传递给 ModelForm 以在 ModelChoiceField 查询中使用

python - 从 numpy.datetime64 转换为 pandas.tslib.Timestamp 错误?

python - 更改 matplotlib 中内联的文本样式

matplotlib - 在 PyQt (pyqtgraph) 中嵌入 "Figure Type"Seaborn Plot

python - 在 QListFiew 中过滤/搜索 QFileSystemModel(可能是 QSortFilterProxyModel)