如何修改QT设计器生成的现有PlotWidget的viewbox?

Posted

技术标签:

【中文标题】如何修改QT设计器生成的现有PlotWidget的viewbox?【英文标题】:How to modify viewbox of existing PlotWidget,which is generated by QT designer? 【发布时间】:2020-03-26 04:30:53 【问题描述】:

我需要从绘图中选择并获取两个图形的数​​据,我找到了一个示例,它创建了一个自定义视图框,然后创建了一个像 pw = pg.PlotWidget(viewBox=vb) 这样的绘图,但我没有当我们将情节作为 Qt Creator 推广的 pyqtgraph 小部件时知道要这样做,在我在论坛中找到的示例下方(链接:https://groups.google.com/forum/#!topic/pyqtgraph/pTrem1RCKSw) 这是代码(完美运行)

import numpy as np
import pyqtgraph as pg
from pyqtgraph.Point import Point
from pyqtgraph.graphicsItems.ItemGroup import ItemGroup
from pyqtgraph.Qt import QtGui, QtCore
from matplotlib.mlab import inside_poly
from pyqtgraph.graphicsItems import ScatterPlotItem


class ChildGroup(ItemGroup):
    sigItemsChanged = QtCore.Signal()
    def __init__(self, parent):
        ItemGroup.__init__(self, parent)
        # excempt from telling view when transform changes
        self._GraphicsObject__inform_view_on_change = False
    def itemChange(self, change, value):
        ret = ItemGroup.itemChange(self, change, value)
        if change == self.ItemChildAddedChange or change == self.ItemChildRemovedChange:
            self.sigItemsChanged.emit()   
        return ret

class MyViewBox(pg.ViewBox):

    def mouseDragEvent(self, ev):

        if ev.button() == QtCore.Qt.RightButton:
            ev.ignore()    
        else:
            pg.ViewBox.mouseDragEvent(self, ev)

        ev.accept() 
        pos = ev.pos()
        if ev.button() == QtCore.Qt.RightButton:

            if ev.isFinish():  
                self.rbScaleBox.hide()
                self.ax = QtCore.QRectF(Point(ev.buttonDownPos(ev.button())), Point(pos))
                self.ax = self.childGroup.mapRectFromParent(self.ax) 
                self.Coords =  self.ax.getCoords()  
                self.getdataInRect()
                self.changePointsColors()
            else:
                self.updateScaleBox(ev.buttonDownPos(), ev.pos())

    def getdataInRect(self):
        # Get the data from the Graphicsitem
        self.getDataItem()
        x = self.dataxy[0]
        y = self.dataxy[1]
        # Rect Edges
        Xbl = (self.Coords[0],self.Coords[1]) # bottom left
        Xbr = (self.Coords[2],self.Coords[1]) # bottom right
        Xtr = (self.Coords[2],self.Coords[3]) # top right
        Xtl = (self.Coords[0],self.Coords[3]) # top left
        #Make a list of [(x0,y0),(x1,y1) ...]
        self.xy = list()
        for i in x:
                tmp = (x[i],y[i])
                self.xy.append(tmp)            
        self.insideIndex = inside_poly(self.xy,[Xbl, Xbr, Xtr, Xtl])    

    def getDataItem(self):

        self.ObjItemList = pg.GraphicsScene.items(self.scene(),self.ax)
        self.dataxy = self.ObjItemList[0].listDataItems()[0].getData()

    def changePointsColors(self):

        print(self.xy)
        print(self.insideIndex)

app = QtGui.QApplication([])
mw = QtGui.QMainWindow()
mw.resize(800,500)
mw.show()

vb = MyViewBox()
pw = pg.PlotWidget(viewBox=vb) 

a  = np.array([0,1,2,3,4,5,6,7,8,9,10])
b  = np.array([0,1,2,3,4,5,6,7,8,9,10])

curve0 = pw.plot(a,b, clickable=True, symbol = '+')

mw.setCentralWidget(pw)

# Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

我怎样才能使以前的代码适应 PlotWidget “Plot1”?

class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
    pg.setConfigOption('background', 'w')
    QtWidgets.QMainWindow.__init__(self)
    Ui_MainWindow.__init__(self)
    self.setupUi(self)

    self.Plot1.plotItem.showGrid(True, True, 0.7)

    self.Plot1.setLabel('left', 'q1')
    self.Plot1.setLabel('bottom', 'Time', units='s')
    self.Plot1.setTitle(title='q1')

    pen = pg.mkPen('color': "FF0000", 'width': 2)
    pen1 = pg.mkPen('color': "00FF00", 'width': 2)
    self.Plot1.addLegend()
    self.q1z = self.Plot1.plot(pen = pen, name = 'Trace 1')
    self.q1k = self.Plot1.plot(pen = pen1, name = 'Trace 2')

这里是文件Sample.ui

有人可以帮我吗?

【问题讨论】:

【参考方案1】:

解决方案是创建一个从 PlotWidget 继承的类,并有一个 Viewbox 到 MyViewBox,然后提升该小部件:

plotwidget.py

import numpy as np

import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore


try:
    from matplotlib.mlab import inside_poly
except ImportError:
    # https://matplotlib.org/3.1.0/api/api_changes.html
    # mlab.inside_poly has been removed in matplotlib 3.1.0
    from matplotlib.path import Path

    def inside_poly(points, verts):
        poly = Path(verts)
        return [idx for idx, p in enumerate(points) if poly.contains_point(p)]


class ChildGroup(pg.ItemGroup):
    sigItemsChanged = QtCore.Signal()

    def __init__(self, parent):
        super(ChildGroup, self).__init__(parent)
        # excempt from telling view when transform changes
        self._GraphicsObject__inform_view_on_change = False

    def itemChange(self, change, value):
        ret = ItemGroup.itemChange(self, change, value)
        if change == self.ItemChildAddedChange or change == self.ItemChildRemovedChange:
            self.sigItemsChanged.emit()
        return ret


class MyViewBox(pg.ViewBox):
    def mouseDragEvent(self, ev):

        if ev.button() == QtCore.Qt.RightButton:
            ev.ignore()
        else:
            pg.ViewBox.mouseDragEvent(self, ev)

        ev.accept()
        pos = ev.pos()
        if ev.button() == QtCore.Qt.RightButton:
            if ev.isFinish():
                self.rbScaleBox.hide()
                self.ax = QtCore.QRectF(
                    pg.Point(ev.buttonDownPos(ev.button())), pg.Point(pos)
                )
                self.ax = self.childGroup.mapRectFromParent(self.ax)
                self.Coords = self.ax.getCoords()
                self.getdataInRect()
                self.changePointsColors()
            else:
                self.updateScaleBox(ev.buttonDownPos(), ev.pos())

    def getdataInRect(self):
        # Get the data from the Graphicsitem
        self.getDataItem()
        x = self.dataxy[0]
        y = self.dataxy[1]
        # Rect Edges
        Xbl = (self.Coords[0], self.Coords[1])  # bottom left
        Xbr = (self.Coords[2], self.Coords[1])  # bottom right
        Xtr = (self.Coords[2], self.Coords[3])  # top right
        Xtl = (self.Coords[0], self.Coords[3])  # top left
        # Make a list of [(x0,y0),(x1,y1) ...]
        self.xy = list()
        for i in x:
            tmp = (x[i], y[i])
            self.xy.append(tmp)
        self.insideIndex = inside_poly(self.xy, [Xbl, Xbr, Xtr, Xtl])

    def getDataItem(self):

        self.ObjItemList = pg.GraphicsScene.items(self.scene(), self.ax)
        self.dataxy = self.ObjItemList[0].listDataItems()[0].getData()

    def changePointsColors(self):
        print(self.xy)
        print(self.insideIndex)


class MyPlotWidget(pg.PlotWidget):
    def __init__(self, parent=None):
        super(MyPlotWidget, self).__init__(parent, viewBox=MyViewBox())

Sample.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>487</width>
    <height>368</height>
   </rect>
  </property>
  <property name="palette">
   <palette>
    <active>
     <colorrole role="Base">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>255</red>
        <green>255</green>
        <blue>255</blue>
       </color>
      </brush>
     </colorrole>
     <colorrole role="Window">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>86</red>
        <green>86</green>
        <blue>86</blue>
       </color>
      </brush>
     </colorrole>
    </active>
    <inactive>
     <colorrole role="Base">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>255</red>
        <green>255</green>
        <blue>255</blue>
       </color>
      </brush>
     </colorrole>
     <colorrole role="Window">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>86</red>
        <green>86</green>
        <blue>86</blue>
       </color>
      </brush>
     </colorrole>
    </inactive>
    <disabled>
     <colorrole role="Base">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>86</red>
        <green>86</green>
        <blue>86</blue>
       </color>
      </brush>
     </colorrole>
     <colorrole role="Window">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>86</red>
        <green>86</green>
        <blue>86</blue>
       </color>
      </brush>
     </colorrole>
    </disabled>
   </palette>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <property name="leftMargin">
    <number>30</number>
   </property>
   <property name="topMargin">
    <number>40</number>
   </property>
   <property name="rightMargin">
    <number>40</number>
   </property>
   <property name="bottomMargin">
    <number>30</number>
   </property>
   <item>
    <widget class="MyPlotWidget" name="Plot1">
     <property name="autoFillBackground">
      <bool>false</bool>
     </property>
     <property name="backgroundBrush">
      <brush brushstyle="SolidPattern">
       <color alpha="255">
        <red>0</red>
        <green>0</green>
        <blue>0</blue>
       </color>
      </brush>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <customwidgets>
  <customwidget>
   <class>MyPlotWidget</class>
   <extends>QGraphicsView</extends>
   <header>plotwidget</header>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
pyuic5 Sample.ui -o sample.py -x

ma​​in.py

from PyQt5 import QtWidgets

import pyqtgraph as pg

from sample import Ui_Dialog


class MyApp(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        pg.setConfigOption("background", "w")
        self.setupUi(self)
        self.Plot1.plotItem.showGrid(True, True, 0.7)
        self.Plot1.setLabel("left", "q1")
        self.Plot1.setLabel("bottom", "Time", units="s")
        self.Plot1.setTitle(title="q1")

        pen = pg.mkPen("color": "FF0000", "width": 2)
        pen1 = pg.mkPen("color": "00FF00", "width": 2)
        self.Plot1.addLegend()
        self.q1z = self.Plot1.plot(pen=pen, name="Trace 1")
        self.q1k = self.Plot1.plot(pen=pen1, name="Trace 2")


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MyApp()
    w.show()
    sys.exit(app.exec_())
├── main.py
├── plotwidget.py
├── sample.py
└── Sample.ui

【讨论】:

对不起,我之前没有回答,因为我的电脑的 w10 已经更新,它不再工作了((,现在我刚刚安装了 w10。谢谢你的朋友,它工作得很好。 我注意到当我绘制矩形选择数据时,如果矩形位于X轴下,那么self.ObjItemList = pg.GraphicsScene.items(self.scene(), self .ax) 返回空,所以如果我想选择位于 x 轴下方的数据,我必须确保矩形至少有一个顶点位于 x 轴上方。有什么建议吗?

以上是关于如何修改QT设计器生成的现有PlotWidget的viewbox?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Designer-qt5 中推广的 PlotWidget() 上制作十字线鼠标跟踪器

如何在 PlotWidget 内制作标签?

Qt:如何将类连接到自定义 Qt 设计器小部件

Qt中用设计器建立的窗口和用代码生成的窗口,为啥拖拽窗口大小的效果不一样?

Qt Creator - 如何查看设计器的代码?

Pyqtgraph plotwidget:无法将轴刻度的字体粗细更改为 BOLD