【问题标题】:Interactive QDialog to show Matplotlib plot交互式 QDialog 显示 Matplotlib 图
【发布时间】:2019-10-12 10:45:50
【问题描述】:

我有一个 python (2.7) 程序 (myGraph.py),它使用 matplotlib 通过函数 showGraph() 创建一个图形。

现在我从 QDialog 调用这个函数 showGraph() 来显示如下图:

import myGraph
# ...
# ....
class myTable(QDialog):

# ...
# ...
    myGraph.showGraph(graphName)

与“graphName”相关的图表正确显示,但 QDialog (myTable) 几乎立即重新出现在图表上方,我无法仔细查看图表,例如展开和滚动它。为此,我必须关闭我不希望的 QDialog (myTable)。因为,我必须看到从 QDialog 中选择的不同 graphName 上传递的不同图形。

所以,基本上我希望从 QDialog 中选择一个“graphName”并调用我的 matplotlib 程序来查看图形,仔细检查它。在此期间,我的 QDialog 应该在图表后面。一旦我关闭图表,QDialog 应该会重新出现,然后我会从对话框中选择一个新的“graphName”并仔细检查它,等等。

程序框架如下:

=============1。分析器.py==================================

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox
from PyQt5 import uic
from PyQt5.QtCore import QCoreApplication

Ui_MainWindwo, QtBaseClass = uic.loadUiType('analyser.ui')

class MyApp(QMainWindow):

    super(MyApp, self).__init__()
    self.ui = Ui.MainWindow()
    self.ui.setupUi(self)

    self.ui.alertPushButton.clicked.connect(self.createAlerts)

:
: ## different other signal-slot connections etc.
:

    def createAlerts(self):

:
:   ##Building up of a list 'alrtLst'
:   ##for example final alrtLst is:

        alrtLst = [['Graph1', 'Sales1-3', 'ABM', '200'],
                   ['Graph2', 'Sales4-8', 'KNT', '500'],
                   ['Graph3', 'Sales9-10', 'MT', '400'],
                   ['Graph4', 'Sales11-12', 'TSL', '500']]

        from alertTable import AlertTable
        alert_table = AlertTable(alrtLst)
        alert_table.exec_()

if __name__ == '__main__':
    app = QCoreApplcation.instance()
    if app is None:
        app = QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

=============2。 alertTable.py=================================

from PyQt5.QtWidgets import QDialog, QTableWidgetItem
from PyQt5 import uic
import myGraph  ##myGraph.py program

class AlertTable(QDialog):
    def __init__(self, alrtLst):
        super(AlertTable, self).__init__()
        uic.loadUi('mytable.ui', self)

        self.tableWidget.doubleClicked.connect(self.tableClick)

        self.tableWidget.setColumnCount(4)
        header_labels = ['Label1', 'Label2', 'Label3', 'Label4']
        self.tableWidget.setHorizontalHeaderLabels(header_labels)

        for row in alrtLst:
            inx = alrtLst.index(row)
            self.tableWidget.insertRow(inx)
            self.tableWidget.setItem(inx,0,QTableWidgetItem(str(row[0])))
            self.tableWidget.setItem(inx,1,QTableWidgetItem(str(row[1])))
            self.tableWidget.setItem(inx,2,QTableWidgetItem(str(row[2])))
            self.tableWidget.setItem(inx,3,QTableWidgetItem(str(row[3])))

    def tableClick(self):
        row = self.tableWidget.currentItem().row()
        cell = self.tableWidget.item(row, 0),text()

        myGraph.showGraph(cell)

=============3。 myGraph.py=================================

import matplotlib.pyplot as plt

def showGraph(grphName):

    dfc = pd.read_csv('E:\\analyzedFiles\\'+grphName+'.csv')
    :
    : ##Construct graph
    :

plt.show()

=============4。 Analyzer.ui==================================

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>shareAnlyserMainWindow</class>
 <widget class="QMainWindow" name="anlyserMainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>484</width>
    <height>278</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Analyser</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout_3">
    <item row="6" column="0" colspan="3">
     <layout class="QGridLayout" name="gridLayout_2">
      <item row="0" column="0">
       <widget class="QProgressBar" name="progressBar">
        <property name="value">
         <number>24</number>
        </property>
       </widget>
      </item>
      <item row="1" column="0">
       <spacer name="verticalSpacer_3">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>40</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
    <item row="0" column="0" colspan="5">
     <widget class="QLabel" name="label">
      <property name="font">
       <font>
        <pointsize>28</pointsize>
        <weight>75</weight>
        <bold>true</bold>
       </font>
      </property>
      <property name="text">
       <string>ANALYSER</string>
      </property>
      <property name="alignment">
       <set>Qt::AlignCenter</set>
      </property>
     </widget>
    </item>
    <item row="1" column="0" colspan="5">
     <widget class="Line" name="line">
      <property name="orientation">
       <enum>Qt::Horizontal</enum>
      </property>
     </widget>
    </item>
    <item row="4" column="0">
     <spacer name="verticalSpacer_5">
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
      <property name="sizeHint" stdset="0">
       <size>
        <width>20</width>
        <height>15</height>
       </size>
      </property>
     </spacer>
    </item>
    <item row="3" column="3" rowspan="4">
     <widget class="Line" name="line_2">
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
    </item>
    <item row="2" column="2">
     <spacer name="verticalSpacer">
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
      <property name="sizeHint" stdset="0">
       <size>
        <width>20</width>
        <height>0</height>
       </size>
      </property>
     </spacer>
    </item>
    <item row="3" column="4" rowspan="4">
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QPushButton" name="consolidatePushButton">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="toolTip">
         <string>Consolidate all daily data</string>
        </property>
        <property name="text">
         <string>Consolidate</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="analysePushButton">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="toolTip">
         <string>Analyse each value movement</string>
        </property>
        <property name="text">
         <string>Analyse</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="alertPushButton">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="toolTip">
         <string>Create alerts for significant movement of specific company value</string>
        </property>
        <property name="text">
         <string>Create Alert</string>
        </property>
       </widget>
      </item>
      <item>
       <spacer name="verticalSpacer_4">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>58</height>
         </size>
        </property>
       </spacer>
      </item>
      <item>
       <widget class="QPushButton" name="exitPushButton">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="toolTip">
         <string>Exit application</string>
        </property>
        <property name="text">
         <string>E&amp;xit</string>
        </property>
       </widget>
      </item>
      <item>
       <spacer name="verticalSpacer_6">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>28</height>
         </size>
        </property>
       </spacer>
      </item>
      <item>
       <widget class="QLabel" name="label_5">
        <property name="text">
         <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;right&quot;&gt;&amp;#169;Bidyut&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
        </property>
        <property name="textFormat">
         <enum>Qt::AutoText</enum>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item row="3" column="0" colspan="3">
     <layout class="QGridLayout" name="gridLayout">
      <item row="0" column="0">
       <widget class="QLabel" name="label_2">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="text">
         <string>Current Month</string>
        </property>
       </widget>
      </item>
      <item row="0" column="1">
       <widget class="QComboBox" name="monthComboBox">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <item>
         <property name="text">
          <string>Select Month ...</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>January</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>February</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>March</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>April</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>May</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>June</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>July</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>August</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>September</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>October</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>November</string>
         </property>
        </item>
        <item>
         <property name="text">
          <string>December</string>
         </property>
        </item>
       </widget>
      </item>
      <item row="0" column="2" colspan="2">
       <spacer name="horizontalSpacer_2">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>128</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
      <item row="1" column="0">
       <widget class="QLabel" name="label_3">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="text">
         <string>Current Year</string>
        </property>
       </widget>
      </item>
      <item row="1" column="1">
       <widget class="QLineEdit" name="yearLineEdit">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
       </widget>
      </item>
      <item row="1" column="2" colspan="2">
       <spacer name="horizontalSpacer_3">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>128</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
      <item row="2" column="1">
       <spacer name="verticalSpacer_2">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>13</height>
         </size>
        </property>
       </spacer>
      </item>
      <item row="3" column="0" colspan="2">
       <spacer name="horizontalSpacer">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>228</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
      <item row="3" column="2">
       <widget class="QPushButton" name="enterPushButton">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="text">
         <string>Enter</string>
        </property>
       </widget>
      </item>
      <item row="3" column="3">
       <spacer name="horizontalSpacer_4">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>58</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
    <item row="4" column="1">
     <layout class="QHBoxLayout" name="horizontalLayout">
      <item>
       <widget class="QLabel" name="label_4">
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
        <property name="text">
         <string>Selected Year Block:</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QLabel" name="yearBlockLabel">
        <property name="text">
         <string>xxxx-xxxx,xxxx-xxxx,xxxx-xxxx</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>484</width>
     <height>21</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="actionGetValues"/>
    <addaction name="separator"/>
    <addaction name="actionExit"/>
   </widget>
   <widget class="QMenu" name="menuProcess">
    <property name="title">
     <string>Process</string>
    </property>
    <addaction name="actionConsolidate"/>
    <addaction name="actionAnalyse"/>
    <addaction name="actionCreateAlert"/>
   </widget>
   <widget class="QMenu" name="menuHelp">
    <property name="title">
     <string>Help</string>
    </property>
    <addaction name="actionAbout"/>
    <addaction name="actionTutorial"/>
   </widget>
   <widget class="QMenu" name="menuSettings">
    <property name="title">
     <string>Settings</string>
    </property>
    <addaction name="actionSetTI"/>
   </widget>
   <addaction name="menuFile"/>
   <addaction name="menuProcess"/>
   <addaction name="menuSettings"/>
   <addaction name="menuHelp"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="actionExit">
   <property name="text">
    <string>E&amp;xit</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+X</string>
   </property>
  </action>
  <action name="actionConsolidate">
   <property name="text">
    <string>&amp;Consolidate</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+Shift+C</string>
   </property>
   <property name="shortcutContext">
    <enum>Qt::ApplicationShortcut</enum>
   </property>
  </action>
  <action name="actionAnalyse">
   <property name="text">
    <string>&amp;Analyse</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+Shift+A</string>
   </property>
  </action>
  <action name="actionCreateAlert">
   <property name="text">
    <string>Create A&amp;lert</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+L</string>
   </property>
  </action>
  <action name="actionAbout">
   <property name="text">
    <string>A&amp;bout</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+B</string>
   </property>
  </action>
  <action name="actionTutorial">
   <property name="text">
    <string>&amp;Tutorial</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+T</string>
   </property>
  </action>
  <action name="actionGetValues">
   <property name="text">
    <string>GetValues</string>
   </property>
  </action>
  <action name="actionSetTI">
   <property name="text">
    <string>Technical Indicators</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

=============5。 myTable.ui=================================

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>trytable</class>
 <widget class="QDialog" name="trytable">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>551</width>
    <height>347</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Try Table</string>
  </property>
  <widget class="QWidget" name="">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>50</y>
     <width>501</width>
     <height>291</height>
    </rect>
   </property>
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QTableWidget" name="tableWidget"/>
    </item>
    <item>
     <widget class="QPushButton" name="pushButton">
      <property name="text">
       <string>Show Table</string>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QPushButton" name="closeButton">
      <property name="text">
       <string>Close</string>
      </property>
     </widget>
    </item>
    <item>
     <spacer name="verticalSpacer">
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
      <property name="sizeHint" stdset="0">
       <size>
        <width>20</width>
        <height>18</height>
       </size>
      </property>
     </spacer>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

【问题讨论】:

  • @S.Nick,按照建议修改了问题。谢谢
  • 抱歉,我无法重现您的问题,因为您还没有发布analyser.ui 和mytable.ui
  • @S.尼克,是的,我明白。我已经包含了 .ui 文件。但是,您已经给出了解决方案。请检查我在 约束 上给出的评论并帮助我。谢谢。

标签: python python-2.7 matplotlib pyqt pyqt5


【解决方案1】:

尝试改变:

    alert_table = AlertTable(alrtLst)
    alert_table.exec_()

开:

     self.alert_table = AlertTable(alrtLst)
     self.alert_table.show()         # or  open() 

# Analyser.py
import sys
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QPushButton
from PyQt5 import uic
from PyQt5.QtCore import QCoreApplication

from PyQt5.QtWidgets import QDialog, QTableWidgetItem
import matplotlib.pyplot as plt

import pandas as pd
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


def showGraph(grphName):
    # +++
    self.figure = plt.figure(figsize=(15,5))              
    self.figure.set_facecolor('0.915')
    self.canvas = FigureCanvas(self.figure) 

#    dfc = pd.read_csv('D:/_Qt/__Qt/'+grphName+'.csv')
    dfc = pd.read_csv('D:/_Qt/__Qt/grphName.csv')             # 

    #    : ##Construct graph
    # plt.show()


#Ui_MainWindwo, QtBaseClass = uic.loadUiType('analyser.ui')
class AlertTable(QDialog):
    def __init__(self, alrtLst):
        super(AlertTable, self).__init__()
#        uic.loadUi('mytable.ui', self)

        self.tableWidget = QTableWidget(self)                   
        self.tableWidget.doubleClicked.connect(self.tableClick)

        self.tableWidget.setColumnCount(4)
        header_labels = ['Label1', 'Label2', 'Label3', 'Label4']
        self.tableWidget.setHorizontalHeaderLabels(header_labels)

        for row in alrtLst:
            inx = alrtLst.index(row)
            self.tableWidget.insertRow(inx)
            self.tableWidget.setItem(inx,0,QTableWidgetItem(str(row[0])))
            self.tableWidget.setItem(inx,1,QTableWidgetItem(str(row[1])))
            self.tableWidget.setItem(inx,2,QTableWidgetItem(str(row[2])))
            self.tableWidget.setItem(inx,3,QTableWidgetItem(str(row[3])))

        # +++            
        self.figure = plt.figure(figsize=(15,5))
        self.figure.set_facecolor('0.915')
        self.canvas = FigureCanvas(self.figure) 

    def tableClick(self):
        row = self.tableWidget.currentItem().row()
#        cell = self.tableWidget.item(row, 0),text()      # - ,text()
        cell = self.tableWidget.item(row, 0).text()       # + .text()

#        myGraph.showGraph(cell)
        self.showGraph(cell)

    # +++        
    def showGraph(self, grphName):
        dfc, _ = QFileDialog.getOpenFileName(self, 'Open file', '/Data/', "CSV Files (*.csv)") # +++
        df = pd.read_csv(str(dfc))
        x = df.x.tolist()
        y = df.y.tolist()
        # Create Figure
        self.figure.clf()
        ax = self.figure.add_subplot(111)
        ax.plot(x, y)
        ax.set_facecolor('0.915')
        ax.set_title('Graphique')
        # Draw Graph
        self.canvas.draw()


class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
#        self.ui = Ui_MainWindwo()   # Ui.MainWindow()
#        self.ui.setupUi(self)

        self.ui = self
        self.ui.alertPushButton = QPushButton("alertPushButton", self)
        self.ui.alertPushButton.clicked.connect(self.createAlerts)

    #: ## different other signal-slot connections etc.

        # +++
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        layout = QVBoxLayout(centralWidget)
        layout.addWidget(self.ui.alertPushButton)

        alrtLst = [['Graph1', 'Sales1-3', 'ABM', '200'],
                   ['Graph2', 'Sales4-8', 'KNT', '500'],
                   ['Graph3', 'Sales9-10', 'MT', '400'],
                   ['Graph4', 'Sales11-12', 'TSL', '500']]
        # +++                   
        self.alert_table = AlertTable(alrtLst)
        layout.addWidget(self.alert_table.canvas)

    def createAlerts(self):
        #:   ##Building up of a list 'alrtLst'
        #:   ##for example final alrtLst is:

#        alert_table.exec_()                             # <<<--- 
        self.alert_table.show()    # or open()           # <<<--- 

if __name__ == '__main__':
#    app = QCoreApplcation.instance()
#    if app is None:
    app = QApplication(sys.argv)

    window = MyApp()
    window.show()
    sys.exit(app.exec_())

【讨论】:

  • 谢谢@Nick。但是,如果我在 QDialog 中嵌入 matplotlib 绘图,那么我会错过 matplotlib 导航栏 和 十字准线 等。我一定需要它们。这就是为什么我直接通过myGraph.showGraph(cell) 运行我的情节。我也希望情节全屏显示。希望你能理解我的需要。请帮帮我。
  • 再次感谢您为解决我的问题所付出的努力。但是,我现在已经在您的帮助下以及在其他关于 stackoverflow 的讨论的帮助下做到了。只剩下一个小问题,我一定会解决它,带有“画布”的 QDialog 出现了两次!一个没有情节,另一个有情节(?)。我可以按照您的建议使用单独的 QDialog 将 matplot navigation 放入其中。再次感谢。
  • @BidyutChakraborty 我认为没有必要在 cmets 中讨论我们没有看到的内容。您应该打开一个新问题,当然还要附上最新版本的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
相关资源
最近更新 更多