我正在尝试使用Filepicker选择要解析的文本文件,并使用主GUI(Qwidget)编写解析器。
它将打开另一个Qwidget作为弹出窗口以执行某些类型的解析。
这一切现在都有效。我想通过解析数据并使用matplotlib将其绘制成图形来添加一些额外的功能。
我在使用matplotlib检查按钮示例来使用pyqt5实现交互式嵌入式图形时遇到了麻烦。在我的代码中,它是PopUpUsageGraphs类。该图有效,但是我看不到复选框。我的主要要求是隐藏和取消隐藏图形中的线。我也可以使用图例选择示例,但它也不适用于我的pyqt5实现。
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from cmsparser import CMSParser
import sip
import sys
import logging
import re
import itertools
from collections import OrderedDict
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.widgets import CheckButtons
# Helper class to display the parsed USAGE Graphs
class PopUpUsageGraphs(QWidget):
def __init__(self, servername, file):
super(PopUpUsageGraphs, self).__init__()
# Get Logger as a global for class
self.logger = logging.getLogger('App')
#Window Property
self.title = 'USAGE Graphs - ' + str(servername)
self.left = 300
self.top = 250
self.width = 1280
self.height = 720
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.file = file
self.mainLayout = QVBoxLayout()
self.test = PlotCanvas1(self, width=7, height=4)
self.toolbar = NavigationToolbar(self.test, self)
self.mainLayout.addWidget(self.toolbar)
self.mainLayout.addWidget(self.test)
self.setLayout(self.mainLayout)
class PlotCanvas1(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
fig.tight_layout()
def plot(self):
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2 * np.pi * t)
s1 = np.sin(4 * np.pi * t)
s2 = np.sin(6 * np.pi * t)
ax = self.figure.add_subplot(111)
l0, = ax.plot(t, s0, visible=False, lw=2)
l1, = ax.plot(t, s1, lw=2)
l2, = ax.plot(t, s2, lw=2)
fig.subplots_adjust(left=0.2)
rax = self.axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True))
self.axes.set_xlabel('Time')
self.axes.set_ylabel('my ydata')
ax.set_title('PyQt Matplotlib Example')
def func(label):
if label == '2 Hz':
l0.set_visible(not l0.get_visible())
elif label == '4 Hz':
l1.set_visible(not l1.get_visible())
elif label == '6 Hz':
l2.set_visible(not l2.get_visible())
self.draw()
check.on_clicked(func)
self.draw()
class App(QWidget):
def __init__(self):
super().__init__()
#Main Window Property
self.title = 'CMSParser - kedang@cisco.com'
self.left = 100
self.top = 100
self.width = 650
self.height = 400
#Globals
self.file = ""
self.filepath = QLineEdit()
self.sessionoutput = QListWidget()
self.browse_btn = QPushButton('Browse...')
self.parse_btn = QPushButton('Parse...')
self.popups = []
self.usageGraphing = False
self.initUI()
#Get Logger as a global for class
self.logger = logging.getLogger('App')
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.sessionoutput.show()
self.show()
#Main Layout
fileinput = QGroupBox("File Input")
top_layout = QFormLayout()
top_layout.addRow(self.browse_btn, self.filepath)
fileinput.setLayout(top_layout)
parseroutput = QGroupBox("Session")
output_layout = QVBoxLayout()
output_layout.addWidget(self.sessionoutput)
parseroutput.setLayout(output_layout)
logger = QCheckBox('Enable Logging', self)
logger.stateChanged.connect(self.log)
usageGraph = QCheckBox('USAGE Graph', self)
usageGraph.stateChanged.connect(self.usageGraphState)
parserinput = QGroupBox("Start")
bot_layout = QHBoxLayout()
bot_layout.addWidget(self.parse_btn)
bot_layout.addWidget(logger)
bot_layout.addWidget(usageGraph)
bot_layout.addStretch(1)
parserinput.setLayout(bot_layout)
mainLayout = QVBoxLayout()
mainLayout.addWidget(fileinput)
mainLayout.addWidget(parseroutput)
mainLayout.addWidget(parserinput)
self.setLayout(mainLayout)
#Connections
self.browse_btn.clicked.connect(self.filePicker)
self.parse_btn.clicked.connect(self.parse)
self.parse_btn.setEnabled(False)
# QFileDialog to get filename assign to global and update the GUI
# Enable the Parse Button
def filePicker(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', '')
self.parse_btn.setEnabled(True)
if fname[0]:
self.filepath.setText(fname[0])
self.file = fname[0]
# Main parse function that takes file name and instantiate DBParser object
# Call getData for parsed tablename, fields and rows
# Call PopUp to instantiate a PopUp window to display parsed data
def parse(self):
if self.file:
self.logger.info('File Loaded: ' + str(self.file))
self.sessionoutput.addItem('Working on file: \"' + str(self.file) + '\" ...')
try:
parser = CMSParser(self.file)
if parser.isDB():
tablename = parser.getTableName()
#Required to instantiate multiple PopUp objects, saved to global list popups
popup = PopUpTable(tablename, self.file)
popup.setAttribute(Qt.WA_DeleteOnClose)
popup.show()
self.popups.append(popup)
self.sessionoutput.addItem('Processed as CMS Database File..')
self.sessionoutput.addItem('Finished parsing database table: ' + str(tablename))
self.logger.info('Processed as CMS Database File')
self.logger.info('Finished parsing data and instantiating popup to display table: ' + str(tablename))
elif parser.isSyslog():
servername = parser.getServerName()
if self.usageGraphing:
popup = PopUpUsageGraphs(servername, self.file)
popup.setAttribute(Qt.WA_DeleteOnClose)
popup.show()
self.popups.append(popup)
self.sessionoutput.addItem('Processed file as CMS Syslog with USAGE Graphing option..')
self.sessionoutput.addItem('Server: ' + str(servername))
self.logger.info('Processed file as CMS Syslog with USAGE Graphing option')
self.logger.info(
'Finished parsing data and instantiating popup to display USAGE data for Server: ' + str(
servername))
else:
# Required to instantiate multiple PopUp objects, saved to global list popups
popup = PopUpText(servername, self.file)
popup.setAttribute(Qt.WA_DeleteOnClose)
popup.show()
self.popups.append(popup)
self.sessionoutput.addItem('Processed file as CMS Syslog..')
self.sessionoutput.addItem('Server: ' + str(servername))
self.logger.info('Processed file as CMS Syslog')
self.logger.info('Finished parsing data and instantiating popup to display data for Server: ' + str(servername))
else:
self.sessionoutput.addItem('Not a parsable file..')
QMessageBox.warning(self, 'Warning', '\nNot a parsable file')
except:
self.sessionoutput.addItem('Invalid file..')
QMessageBox.critical(self, 'Error', "\nInvalid file")
self.parse_btn.setEnabled(False)