本文整理汇总了Python中matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setFocusPolicy方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasQTAgg.setFocusPolicy方法的具体用法?Python FigureCanvasQTAgg.setFocusPolicy怎么用?Python FigureCanvasQTAgg.setFocusPolicy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg
的用法示例。
在下文中一共展示了FigureCanvasQTAgg.setFocusPolicy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_canvas
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
def create_canvas(self): # pragma: no cover
self.fig = Figure()
canvas = FigureCanvas(self.fig)
self.ui.mainLayout.addWidget(canvas)
canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
# Add subplots
gridspec = GridSpec(2, 4)
self.map_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2)
)
self.spectrum_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2)
)
self.hist_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1)
)
self.edge_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1)
)
# Create the colorbar on the histogram axes
self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax,
cmap="viridis",
norm=Normalize(0, 1))
self.cbar.ax.set_xlabel("Map Value")
# Adjust the margins
self.fig.tight_layout(pad=0)
self.fig.canvas.draw_idle()
示例2: __init__
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
def __init__(self, parent=None, width=6, height=4, dpi=110):
"""
Init canvas.
"""
self.fig = Figure(figsize=(width, height), dpi=dpi)
# Here one can adjust the position of the CTX plot area.
# self.axes = self.fig.add_subplot(111)
self.axes = self.fig.add_axes([0.1, 0.1, 0.85, 0.85])
self.axes.grid(True)
self.axes.set_xlabel("(no data)")
self.axes.set_ylabel("(no data)")
FigureCanvas.__init__(self, self.fig)
layout = QVBoxLayout(parent)
layout.addWidget(self)
parent.setLayout(layout)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# next too lines are needed in order to catch keypress events in plot canvas by mpl_connect()
FigureCanvas.setFocusPolicy(self, QtCore.Qt.ClickFocus)
FigureCanvas.setFocus(self)
示例3: QFigureWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class QFigureWidget(QtWidgets.QWidget):
"""Widget to layout the actual figure and toolbar. Further it forwards.
the key press events from the widget to the figure."""
def __init__(self, fig, *args, **kw):
super(QFigureWidget, self).__init__(*args, **kw)
self.fig = fig
self.canvas = FigureCanvasQTAgg(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
self.canvas.setFocus()
color = fig.get_facecolor()
self.toolbar = QNavigationToolbar(self.canvas, self)
self.toolbar.setStyleSheet("QNavigationToolbar { background-color: %s }"
%rgb2hex(color))
self.toolbar.setIconSize(QtCore.QSize(16, 16))
self.canvas.mpl_connect('key_press_event', self.on_key_press)
vbox = QtWidgets.QVBoxLayout(self)
vbox.addWidget(self.canvas)
vbox.addWidget(self.toolbar)
vbox.setContentsMargins(0, 0, 0, 0)
vbox.setSpacing(0)
def hideToolbar(self):
self.toolbar.hide()
def showToolbar(self):
self.toolbar.show()
def close(self):
super(QFigureWidget, self).close()
def on_key_press(self, event):
# sometimes mpl has a weird ideas what oo-programing is.
# any could overwrite method by my self
# no fullscreen unless self is a window!
if event.key == "t":
self.toolbar.toggle()
elif event.key not in rcParams["keymap.fullscreen"]:
key_press_handler(event, self.canvas, self.toolbar)
示例4: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
#.........这里部分代码省略.........
except:
self.molformulaLabel = QLabel("<b>Mol. Formula:</b> Unknown")
self.molwtLabel = QLabel("<b>Mol. Weight:</b> Unknown")
self.structure.setText("No Structure Available")
self.structure.setAlignment(Qt.AlignCenter)
else:
self.smilesLabel = QLabel("<b>SMILES:</b> Unknown")
self.molformulaLabel = QLabel("<b>Mol. Formula:</b> Unknown")
self.molwtLabel = QLabel("<b>Mol. Weight:</b> Unknown")
self.structure.setText("No Structure Available")
self.structure.setAlignment(Qt.AlignCenter)
self.editinfoButton = QPushButton('Edit Compound Info')
self.editinfoButton.setToolTip("Opens a window to edit compound information") # TODO: Set tooltip
self.restoreinfoButton = QPushButton('Restore Compound Info')
self.restoreinfoButton.setToolTip("Resets compound information to original imported values") # TODO: Set tooltip
self.savestructureButton = QPushButton('Save Structure Image')
self.savestructureButton.setToolTip("Tooltip") # TODO: Set tooltip
def initSpectrum(self):
# Compound Spectrum Tab
matplotlib.projections.register_projection(My_Axes)
self.scale = 1.05
self.show_ignored = True
self.show_ignored_peaks = True
self.compoundtab2 = QWidget()
self.compoundtab2.setStyleSheet("QWidget{background-color: white;}")
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis / Scroll-wheel to change intensity scale"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 10px;}')
self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
self.showignoredregionsCheckBox.setToolTip("Shows the ranges set by the solvent/buffer ignore regions, if any.")
self.showignoredregionsCheckBox.setLayoutDirection(Qt.RightToLeft)
self.showignoredregionsCheckBox.setChecked(True)
self.showignoredpeaksCheckBox = QCheckBox("Show Ignored Peaks")
self.showignoredpeaksCheckBox.setToolTip("Shows any compound peaks that are in the solvent/buffer ignore regions, if any.\n"
"These peaks are ignored and are not evaluated during mixing.")
self.showignoredpeaksCheckBox.setLayoutDirection(Qt.RightToLeft)
self.showignoredpeaksCheckBox.setChecked(True)
self.resetviewButton = QPushButton("Reset View")
self.resetviewButton.setToolTip("Resets the spectrum to the default view.")
self.savespectrumButton = QPushButton("Save Spectrum")
self.savespectrumButton.setToolTip("Saves the image in the spectrum window.")
def initPeaklistTable(self):
# Compound Peaklist Tab
self.compoundtab3 = QWidget()
self.compoundtab3.setStyleSheet("QWidget{background-color: white;}")
self.peakTable = QTableWidget(0, 4, self)
# self.peakTable.setMinimumWidth(400)
self.peakTable.setSelectionMode(QAbstractItemView.NoSelection)
self.peakTable.setSelectionBehavior(QAbstractItemView.SelectRows)
示例5: VisualizerDialog
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
#.........这里部分代码省略.........
kwargs["func_y"] = None
kwargs["column_y"] = utf8(self.combo_y_function.currentText())
if self.visualizer.numerical_axes == 1:
try:
kwargs["func_x"] = self._function_list[self.combo_x_function.currentIndex()]
kwargs["column_x"] = None
except IndexError:
kwargs["func_x"] = None
kwargs["column_x"] = utf8(self.combo_x_function.currentText())
self.visualizer.setup_figure()
self.remove_matplot()
self.add_matplot()
self.visualizer.draw(**kwargs)
self.visualizer.g.fig.tight_layout()
self.visualizer.adjust_axes()
self.visualizer.adjust_fonts()
if self.smooth:
self.spinner.setEnabled(True)
self.visualizer.g.fig.tight_layout()
if hasattr(self.toolbar, "margin_dialog"):
self.toolbar.configure_subplots()
def add_matplot(self):
""" Add a matplotlib canvas and a navigation bar to the dialog. """
if not self.canvas:
self.canvas = FigureCanvas(self.visualizer.g.fig)
self.ui.verticalLayout.addWidget(self.canvas)
self.canvas.setParent(self.ui.box_visualize)
self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
self.canvas.setFocus()
if not self.toolbar:
self.toolbar = CoqNavigationToolbar(self.canvas, self, True)
if (self.visualizer.numerical_axes == 2 and
self.visualizer.function_list):
self.toolbar.addWidget(self.label_y_function)
self.toolbar.addWidget(self.combo_y_function)
if (self.visualizer.numerical_axes == 1 and
self.visualizer.function_list):
self.toolbar.addWidget(self.label_x_function)
self.toolbar.addWidget(self.combo_x_function)
if options.cfg.experimental:
self.toolbar.check_freeze.stateChanged.connect(self.toggle_freeze)
if self.smooth:
self.toolbar.addWidget(self.spinner_label)
self.toolbar.addWidget(self.spinner)
self.ui.navigation_layout.addWidget(self.toolbar)
else:
self.toolbar.canvas = self.canvas
self.canvas.mpl_connect('key_press_event', self.keyPressEvent)
self.canvas.mpl_connect('button_press_event', self.onclick)
def onclick(self, event):
"""
Pass any click event onward to the visualizer, unless the dialog is
in panning or zooming mode.
"""
if not self.toolbar.isPanning() and not self.toolbar.isZooming():
self.visualizer.onclick(event)
def remove_matplot(self):
示例6: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class Window(QDialog):
def __init__(self, params_object, library_object, group, parent=None):
QDialog.__init__(self, parent)
self.params = params_object
self.library = library_object
self.group = group
matplotlib.projections.register_projection(My_Axes)
self.region_colors = {0:'gray', 1:'red', 2:'green', 3:'orange', 4:'teal', 5:'pink',
6:'cyan', 7:'magenta', 8:'gold'}
if self.group == 'ALL':
self.plural_group = "s"
else:
self.plural_group = ""
self.setWindowTitle("NMRmix: Peaks Histogram for %s Group%s" % (self.group, self.plural_group))
self.scale = 1.05
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.createMainFrame()
def createMainFrame(self):
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 12px;}')
self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
self.showignoredregionsCheckBox.setChecked(True)
self.showignoredregionsCheckBox.setToolTip("Tooltip") # TODO: Tooltip
self.showignoredregionsCheckBox.stateChanged.connect(self.handleIgnored)
self.closeButton = QPushButton("Close")
self.closeButton.setStyleSheet("QPushButton{color: red; font-weight: bold;}")
self.closeButton.clicked.connect(self.closeEvent)
self.saveButton = QPushButton("Save")
self.saveButton.setStyleSheet("QPushButton{color: green; font-weight: bold;}")
self.saveButton.clicked.connect(self.saveResults)
self.resetButton = QPushButton("Reset")
self.resetButton.setStyleSheet("QPushButton{color: blue; font-weight: bold;}")
self.resetButton.clicked.connect(self.resetGraph)
self.calculateAllHistogram()
self.calculateIntenseHistogram()
self.drawIgnoredRegions()
winLayout = QVBoxLayout(self)
winLayout.addWidget(self.canvas)
winLayout.addWidget(self.instructionLabel)
winLayout.addWidget(self.showignoredregionsCheckBox)
buttonLayout = QHBoxLayout()
buttonLayout.addWidget(self.closeButton)
buttonLayout.addWidget(self.resetButton)
buttonLayout.addWidget(self.saveButton)
winLayout.addLayout(buttonLayout)
winLayout.setAlignment(self.showignoredregionsCheckBox, Qt.AlignCenter)
self.fig.tight_layout(pad=3)
self.canvas.draw()
def calculateAllHistogram(self):
self.ax1 = self.fig.add_subplot(211, projection="My_Axes")
self.ax1.set_title("Peaks Histogram for %s Group%s" % (self.group, self.plural_group), fontweight='bold')
self.ax1.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
self.ax1.set_ylabel("Number of Peaks", fontweight='bold')
data = list(self.library.stats[self.group]['Peaklist'])
y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
self.ax1.set_xlim(self.params.shift_range[self.params.nuclei])
self.upper_ylim_all = max(y)+(math.ceil(max(y)*0.05))
self.ax1.set_ylim([0, self.upper_ylim_all])
self.ax1.plot(bincenters, y, '-', color='blue')
def calculateIntenseHistogram(self):
self.ax2 = self.fig.add_subplot(212, sharex=self.ax1, projection="My_Axes")
self.ax2.set_title("Intense Peaks Histogram for %s Group%s" % (self.group, self.plural_group),
fontweight='bold')
self.ax2.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
self.ax2.set_ylabel("Number of Peaks", fontweight='bold')
data = list(self.library.stats[self.group]['Intense Peaklist'])
y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
self.ax2.set_xlim([12, -1])
self.upper_ylim_intense = max(y)+(math.ceil(max(y)*0.05))
self.ax2.set_ylim([0, self.upper_ylim_intense])
self.ax2.plot(bincenters, y, '-', color='purple')
def resetGraph(self):
self.mpl_toolbar.home()
def drawIgnoredRegions(self):
groups = ['ALL']
if self.group != 'ALL':
groups.append(self.group)
for region in self.library.ignored_regions:
#.........这里部分代码省略.........
示例7: MplGraphQt5Widget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class MplGraphQt5Widget(QWidget):
def __init__(self, parent=None):
super(MplGraphQt5Widget, self).__init__(parent)
self.width = 3
self.height = 3
self.dpi = 100
self._dataY = np.array([])
self._dataX = np.array([])
self._spCols = 1
self._spRows = 1
self.all_sp_axes = []
self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
self.fig.set_frameon(False)
self.fig.set_tight_layout(True)
self.canvas = Canvas(self.fig)
self._navBarOn = False
self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
self.mpl_toolbar.dynamic_update()
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('button_press_event', self.on_button_press)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.setParent(parent)
self.canvas.clearMask()
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.updateGeometry()
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
if not self._navBarOn:
self.mpl_toolbar.hide()
self.setLayout(vbox)
def get_icon(name):
"""Return Matplotlib icon *name*"""
return QIcon(osp.join(rcParams['datapath'], 'images', name))
key_pressed = pyqtSignal(object, name='keyPressed')
def on_key_press(self, event):
self.key_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
button_pressed = pyqtSignal(object, name='buttonPressed')
def on_button_press(self, event):
self.button_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
mouse_move = pyqtSignal(object, name='mouseMoved')
def on_mouse_move(self, event):
self.mouse_move.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
def generateNewAxes(self):
for ax in self.all_sp_axes:
self.fig.delaxes(ax)
self.all_sp_axes = []
numOfAxes = (self._spRows*self._spCols)+1
for i in np.arange(1,numOfAxes):
self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes
self.canvas.updateGeometry() #This will bring the size of the canvas back to the original (defined by the vbox)
spRowsChanged = pyqtSignal(int)
def getspRows(self):
return self._spRows
@pyqtSlot(int)
def setspRows(self, spRows):
self._spRows = spRows
self.generateNewAxes()
self.spRowsChanged.emit(spRows)
def resetspRows(self):
self.setspRows(1)
spRows = pyqtProperty(int, getspRows, setspRows, resetspRows)
spColsChanged = pyqtSignal(int)
def getspCols(self):
return self._spCols
#.........这里部分代码省略.........
示例8: MplWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class MplWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.setParent(self)
self.canvas.mpl_connect('scroll_event', self.onWheel)
self.canvas.mpl_connect('button_press_event', self.start_pan)
self.canvas.mpl_connect('button_release_event', self.pan)
self.canvas.mpl_connect('motion_notify_event', self.pan_motion)
self.axes = self.fig.add_subplot(111)
self.fig.tight_layout()
self.dragx = None
self.dragy = None
# self.mpl_toolbar = NavigationToolbar(self.canvas, self)
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.canvas)
# vbox.addWidget(self.mpl_toolbar)
self.setLayout(vbox)
def start_pan(self, event):
if event.button == 3:
self.dragx, self.dragy = event.xdata, event.ydata
def do_pan(self, xdata, ydata):
diffx, diffy = self.dragx - xdata, self.dragy - ydata
x1, x2 = self.axes.get_xlim()
y1, y2 = self.axes.get_ylim()
self.axes.set_xlim(x1 + diffx, x2 + diffx)
self.axes.set_ylim(y1 + diffy, y2 + diffy)
self.canvas.draw_idle()
def stop_pan(self):
self.dragx, self.dragy = None, None
def pan(self, event):
if event.button == 3:
if event.inaxes is not None and \
self.dragx is not None and self.dragy is not None and \
event.xdata is not None and event.ydata is not None:
self.do_pan(event.xdata, event.ydata)
self.stop_pan()
def pan_motion(self, event):
if event.inaxes is not None and \
self.dragx is not None and self.dragy is not None and \
event.xdata is not None and event.ydata is not None:
self.do_pan(event.xdata, event.ydata)
def _rescale(self, lo, hi, step, pt=None, bal=None, scale='linear'):
"""
Rescale (lo,hi) by step, returning the new (lo,hi)
The scaling is centered on pt, with positive values of step
driving lo/hi away from pt and negative values pulling them in.
If bal is given instead of point, it is already in [0,1] coordinates.
This is a helper function for step-based zooming.
"""
# Convert values into the correct scale for a linear transformation
# TODO: use proper scale transformers
if scale == 'log':
lo, hi = math.log10(lo), math.log10(hi)
if pt is not None: pt = math.log10(pt)
# Compute delta from axis range * %, or 1-% if percent is negative
if step > 0:
delta = float(hi - lo) * step / 100
else:
delta = float(hi - lo) * step / (100 - step)
# Add scale factor proportionally to the lo and hi values, preserving the
# point under the mouse
if bal is None:
bal = float(pt - lo) / (hi - lo)
lo -= bal * delta
hi += (1 - bal) * delta
# Convert transformed values back to the original scale
if scale == 'log':
lo, hi = math.pow(10., lo), math.pow(10., hi)
return (lo, hi)
def onWheel(self, event):
"""
Process mouse wheel as zoom events
"""
ax = event.inaxes
# Older versions of matplotlib do not have event.step defined
try:
step = 20.0 * event.step
except:
if event.button == 'up':
#.........这里部分代码省略.........
示例9: Calibrlogger
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
#.........这里部分代码省略.........
self.ToDateTime.setDateTime(datestring_to_date('2099-12-31 23:59:59'))
self.Add2Levelmasl.setText('')
self.bestFitSearchRadius.setText('10 minutes')
#self.mpltoolbar.home()
last_calibration = self.getlastcalibration(self.obsid)
try:
if last_calibration[0][1] and last_calibration[0][0]:
self.LoggerPos.setText(str(last_calibration[0][1]))
self.FromDateTime.setDateTime(datestring_to_date(last_calibration[0][0]))
else:
self.LoggerPos.setText('')
self.FromDateTime.setDateTime(datestring_to_date('2099-12-31 23:59:59'))
except Exception as e:
utils.MessagebarAndLog.info(log_msg=ru(QCoreApplication.translate('Calibrlogger', 'Getting last calibration failed for obsid %s, msg: %s'))%(self.obsid, str(e)))
self.LoggerPos.setText('')
self.FromDateTime.setDateTime(datestring_to_date('2099-12-31 23:59:59'))
@fn_timer
def reset_cid(self):
""" Resets self.cid to an empty list and disconnects unused events """
for x in self.cid:
self.canvas.mpl_disconnect(x)
self.cid = []
@fn_timer
def catch_old_level(self):
"""Part of adjustment method 3. adjust level_masl by clicking in plot.
this part selects a line node and a y-position on the plot"""
#Run init to make sure self.meas_ts and self.head_ts is updated for the current obsid.
self.load_obsid_and_init()
self.deactivate_pan_zoom()
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Select a logger node.")))
self.cid.append(self.canvas.mpl_connect('pick_event', self.set_log_pos_from_node_date_click))
@fn_timer
def catch_new_level(self):
""" Part of adjustment method 3. adjust level_masl by clicking in plot.
this part selects a y-position from the plot (normally user would select a manual measurement)."""
if self.log_pos is not None:
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Select a y position to move to.")))
self.cid.append(self.canvas.mpl_connect('button_press_event', self.set_y_pos_from_y_click))
self.calib_help.setText("")
else:
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Something wrong, click \"Current\" and try again.")))
@fn_timer
def calculate_offset(self):
""" Part of adjustment method 3. adjust level_masl by clicking in plot.
this method extracts the head from head_ts with the same date as the line node.
4. Calculating y-position - head (or level_masl) and setting self.LoggerPos.
5. Run calibration.
"""
if self.log_pos is not None and self.y_pos is not None:
utils.start_waiting_cursor()
logger_ts = self.level_masl_ts
y_pos = self.y_pos
log_pos = self.log_pos
self.y_pos = None
self.log_pos = None
示例10: VelPlotWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class VelPlotWidget(QWidget):
""" Widget for a velocity plot with interaction.
Akin to XIDL/x_velplot
19-Dec-2014 by JXP
"""
def __init__(self, ispec, z, abs_lines=None, parent=None, llist=None, norm=True,
vmnx=[-300., 300.]*u.km/u.s):
'''
spec : XSpectrum1D
z : float
abs_lines: list, optional
List of AbsLines
llist : LineList, optional
Input line list. Defaults to 'Strong'
norm : bool, optional
Normalized spectrum?
vmnx : Quantity array, optional
Starting velocity range for the widget
'''
super(VelPlotWidget, self).__init__(parent)
self.help_message = """
Click on any white region within the velocity plots
for the following keystroke commands to work:
i,o : zoom in/out x limits
I,O : zoom in/out x limits (larger re-scale)
y : zoom out y limits
t,b : set y top/bottom limit
l,r : set left/right x limit
[,] : pan left/right
C,c : add/remove column
K,k : add/remove row
=,- : move to next/previous page
1,2 : Modify velocity region of the single line (left, right sides)
!,@ : Modify velocity region of all lines (left, right)
A,x : Add/remove select line from analysis list
X : Remove all lines from analysis list
^,& : Flag line to be analyzed for low/high-ion kinematics
B : Toggle as blend/no-blend (orange color = blend)
N : Toggle as do/do-not include for analysis (red color = exclude)
V : Indicate as a normal value
L : Indicate as a lower limit
U : Indicate as a upper limit
? : Print this
"""
# Initialize
spec, spec_fil = ltgu.read_spec(ispec)
self.spec = spec
self.spec_fil = spec_fil
self.z = z
self.vmnx = vmnx
self.norm = norm
# Abs Lines
if abs_lines is None:
self.abs_lines = []
else:
self.abs_lines = abs_lines
#QtCore.pyqtRemoveInputHook()
#xdb.set_trace()
#QtCore.pyqtRestoreInputHook()
self.psdict = {} # Dict for spectra plotting
self.psdict['x_minmax'] = self.vmnx.value # Too much pain to use units with this
self.psdict['y_minmax'] = [-0.1, 1.1]
self.psdict['nav'] = ltgu.navigate(0,0,init=True)
# Line List
if llist is None:
self.llist = ltgu.set_llist('Strong')
else:
self.llist = llist
self.llist['z'] = self.z
# Indexing for line plotting
self.idx_line = 0
self.init_lines()
# Create the mpl Figure and FigCanvas objects.
self.dpi = 150
self.fig = Figure((8.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
self.canvas.setFocus()
self.canvas.mpl_connect('key_press_event', self.on_key)
self.canvas.mpl_connect('button_press_event', self.on_click)
# Sub_plots (Initial)
self.sub_xy = [3,4]
self.fig.subplots_adjust(hspace=0.0, wspace=0.1)
# Layout
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
#.........这里部分代码省略.........
示例11: ExamineSpecWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class ExamineSpecWidget(QWidget):
""" Widget to plot a spectrum and interactively
fiddle about. Akin to XIDL/x_specplot.pro
12-Dec-2014 by JXP
"""
def __init__(self, ispec, parent=None, status=None, llist=None,
abs_sys=None, norm=True, second_file=None, zsys=None,
key_events=True, vlines=None, plotzero=False, exten=None,
xlim=None, ylim=None, rsp_kwargs=None, air=False):
"""
Parameters
----------
ispec : XSpectrum1D, tuple of arrays or filename
exten : int, optional
extension for the spectrum in multi-extension FITS file
parent : Widget parent, optional
status : Point to status bar, optional
llist : dict, optional
Used to guide the line lists
abs_sys : list, optional
AbsSystem's
zsys : float, optional
intial redshift
key_events : bool, optional
Use key events? [True]
Useful when coupling to other widgets
xlim : tuple of two floats
Initial x plotting limits
ylim : tuple of two floats
Initial y plotting limits
air : bool, optional
Spectrum is wavelength calibrated `in air`
"""
super(ExamineSpecWidget, self).__init__(parent)
# Spectrum
spec, spec_fil = ltgu.read_spec(ispec, exten=exten, norm=norm,
rsp_kwargs=rsp_kwargs)
if air:
spec.meta['airvac'] = 'air'
spec.airtovac()
self.orig_spec = spec # For smoothing
self.spec = self.orig_spec
self.parent = parent
# determine the filename (if any)
if isinstance(ispec, (str, basestring)):
filename = ispec
else:
filename = None
self.vlines = []
if vlines is not None:
self.vlines.extend(vlines)
self.plotzero = plotzero
# Other bits (modified by other widgets)
self.model = None
self.bad_model = None # Discrepant pixels in model
self.use_event = 1
# Abs Systems
if abs_sys is None:
self.abs_sys = []
else:
self.abs_sys = abs_sys
self.norm = norm
self.psdict = {} # Dict for spectra plotting
self.adict = {} # Dict for analysis
self.init_spec(xlim=xlim, ylim=ylim)
self.xval = None # Used with velplt
# Status Bar?
if not status is None:
self.statusBar = status
# Line List?
if llist is None:
self.llist = {'Plot': False, 'List': 'None', 'z': 0., 'Lists': []}
else:
self.llist = llist
# zsys
if zsys is not None:
self.llist['z'] = zsys
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 150 # 150
self.fig = Figure((8.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
self.canvas.setFocus()
if key_events:
self.canvas.mpl_connect('key_press_event', self.on_key)
#.........这里部分代码省略.........
示例12: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class Window(QDialog):
def __init__(self, params_object, library_object, group, parent=None):
QDialog.__init__(self, parent)
self.params = params_object
self.library = library_object
self.group = group
matplotlib.projections.register_projection(My_Axes)
self.region_colors = {0:'gray', 1:'red', 2:'green', 3:'orange', 4:'teal', 5:'pink',
6:'cyan', 7:'magenta', 8:'gold'}
if self.group == 'ALL':
self.plural_group = "s"
else:
self.plural_group = ""
self.setWindowTitle("NMRmix: Peak Aromaticity Histogram for %s Group%s" % (self.group, self.plural_group))
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.scale = 1.05
self.mean = np.mean(self.library.stats[group]['Aromaticity'])
self.stdev = np.std(self.library.stats[group]['Aromaticity'])
self.median = np.median(self.library.stats[group]['Aromaticity'])
self.createMainFrame()
def createMainFrame(self):
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
# self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 12px;}')
self.closeButton = QPushButton("Close")
self.closeButton.setStyleSheet("QPushButton{color: red; font-weight: bold;}")
self.closeButton.clicked.connect(self.closeEvent)
self.saveButton = QPushButton("Save")
self.saveButton.setStyleSheet("QPushButton{color: green; font-weight: bold;}")
self.saveButton.clicked.connect(self.saveResults)
self.resetButton = QPushButton("Reset")
self.resetButton.setStyleSheet("QPushButton{color: blue; font-weight: bold;}")
self.resetButton.clicked.connect(self.resetGraph)
self.calculateHistogram()
winLayout = QVBoxLayout(self)
winLayout.addWidget(self.canvas)
winLayout.addWidget(self.instructionLabel)
buttonLayout = QHBoxLayout()
buttonLayout.addWidget(self.closeButton)
buttonLayout.addWidget(self.resetButton)
buttonLayout.addWidget(self.saveButton)
winLayout.addLayout(buttonLayout)
self.fig.tight_layout(pad=3)
self.canvas.draw()
def calculateHistogram(self):
self.ax = self.fig.add_subplot(111, projection="My_Axes")
self.ax.set_title("Peak Aromaticity Histogram for %s Group%s" % (self.group, self.plural_group),
fontweight='bold')
self.ax.set_xlabel("Percentage of Aromatic Peaks (aromatic >= %0.3f ppm)" % self.params.aromatic_cutoff, fontweight='bold')
self.ax.set_ylabel("Number of Compounds", fontweight='bold')
data = list(self.library.stats[self.group]['Aromaticity'])
self.ax.hist(data, bins=range(0, 110, 10), color='red', alpha=0.75, rwidth=0.9)
self.ax.xaxis.set_ticks_position('none')
self.ax.yaxis.set_ticks_position('none')
self.ax.annotate("Mean: %.1f %%" % (self.mean), xy=(0.70, 0.82), xycoords='figure fraction',
horizontalalignment='left')
self.ax.annotate("Median: %.0f %%" % (self.median), xy=(0.70, 0.79), xycoords='figure fraction',
horizontalalignment='left')
def resetGraph(self):
self.mpl_toolbar.home()
def zooming(self, event):
cur_ylim = self.ax.get_ylim()
cur_yrange = (cur_ylim[1] - cur_ylim[0])
if event.button == 'up':
scale_factor = self.scale
elif event.button == 'down':
scale_factor = 1/self.scale
else:
scale_factor = 1
self.ax.set_ylim([0, (cur_yrange*scale_factor)])
self.canvas.draw()
def saveResults(self):
filename = "peakaromaticity.png"
filepath = os.path.join(self.params.work_dir, filename)
filestype = "static (*.png *.jpg *.svg)"
fileObj = QFileDialog.getSaveFileName(self, caption="Save Peak Stats Plot", directory=filepath, filter=filestype)
if fileObj[0]:
self.fig.set_size_inches(12, 8)
plt.savefig(fileObj[0], dpi=200)
def closeEvent(self, event=False):
#.........这里部分代码省略.........
示例13: Plotter
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class Plotter(object):
def __init__(self, masterWindow, style=None, scheme=None):
self.masterWindow = masterWindow
self.legend = False
plotArea = masterWindow.ui.plotArea
# create the plotting canvas and its toolbar and add them
tfig = Figure()
tfig.set_facecolor('white')
self.canvas = FigureCanvasQTAgg(tfig)
self.canvas.setMinimumSize(50, 100)
self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
self.navbar = AstonNavBar(self.canvas, masterWindow)
plotArea.addWidget(self.navbar)
plotArea.addWidget(self.canvas)
self.plt = tfig.add_axes((0.05, 0.1, 0.9, 0.85), frame_on=False)
self.plt.axes.hold(False)
self.plt.xaxis.set_ticks_position('none')
self.plt.yaxis.set_ticks_position('none')
self.patches = []
self.cb = None
# TODO: find a way to make the axes fill the figure properly
# tfig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95)
# tfig.tight_layout(pad=2)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.mpl_connect('button_press_event', self.mousedown)
self.canvas.mpl_connect('button_release_event', self.mouseup)
self.canvas.mpl_connect('scroll_event', self.mousescroll)
self.highlight = None
def plot_data(self, plots, update_bounds=True):
if not update_bounds:
bnds = self.plt.get_xlim(), self.plt.get_ylim()
# clean up anything on the graph already
self.plt.cla()
if self.cb is not None:
#TODO: this should work? need way to update size of mappable axes
#self.plt.figure.delaxes(self.cb.ax)
#self.cb.mappable.axes.autoscale()
#self.cb = None
#the next two lines used to work?
self.plt.figure.delaxes(self.cb.ax)
self.cb = None
tfig = self.plt.figure
tfig.clf()
self.plt = tfig.add_subplot(111, frameon=False)
self.plt.xaxis.set_ticks_position('none')
self.plt.yaxis.set_ticks_position('none')
self.cb = None
self.plt.figure.subplots_adjust(left=0.05, right=0.95)
self.patches = []
#plot all of the datafiles
if len(plots) == 0:
self.canvas.draw()
return
## make up a factor to separate plots by
#if 'stacked' in self._style:
# fts = datafils[0].trace(datafiles[0].info['traces'].split(',')[0])
# sc_factor = (max(fts.data[:, 0]) - min(fts.data[:, 0])) / 5.
## count the number of traces that will be displayed
nplots = len(plots)
if nplots < 6:
alpha = 0.75 - nplots * 0.1
else:
alpha = 0.15
#FIXME: read this from the menu
colors = get_cmap('Spectral')
#TODO: do scaling/scaling with offset/etc?
#TODO: determine the number of axes to use
#TODO: should be filtering out invalid plots before here
for pnum, plot in enumerate(plots):
style = plot.style
if plot.color == 'auto':
if style in {'heatmap', 'colors'}:
c = colors
elif nplots > 7:
c = colors(int(pnum % 7) / 6.0, 1)
elif nplots == 1:
c = colors(0, 1)
else:
c = colors(int(pnum % nplots) / float(nplots - 1), 1)
else:
c = plot.color
if style == 'heatmap':
plot.plot(style=style, color=c, ax=self.plt)
if self.legend:
self.cb = self.plt.figure.colorbar(self.plt.images[0])
elif style == 'colors':
#.........这里部分代码省略.........
示例14: band_graph
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class band_graph(QWidget):
def init(self):
self.main_vbox = QVBoxLayout()
toolbar=QToolBar()
toolbar.setIconSize(QSize(32, 32))
self.tb_save = QAction(QIcon(os.path.join(get_image_file_path(),"save.svg")), "Save image", self)
self.tb_save.setStatusTip(_("Close"))
self.tb_save.triggered.connect(self.callback_save_image)
toolbar.addAction(self.tb_save)
self.main_vbox.addWidget(toolbar)
self.my_figure=Figure(figsize=(5,4), dpi=100)
self.canvas = FigureCanvas(self.my_figure)
self.canvas.mpl_connect('key_press_event', self.press)
self.canvas.setFocusPolicy( Qt.ClickFocus )
self.canvas.setFocus()
self.canvas.figure.patch.set_facecolor('white')
#self.canvas.set_size_request(600, 400)
self.canvas.show()
self.main_vbox.addWidget(self.canvas)
#self.canvas.connect('key_press_event', self.on_key_press_event)
self.setLayout(self.main_vbox)
# def keyPressEvent(self, event):
# pritn("oh")
#
# keyname = ''
# key = event.key()
# modifiers = int(event.modifiers())
# if (Qt.CTRL & modifiers)==modifiers and key==67:
# self.do_clip()
# self.canvas.draw()
def press(self,event):
#print('press', event.key)
sys.stdout.flush()
if event.key == "ctrl+c":
self.do_clip()
def do_clip(self):
buf = io.BytesIO()
self.my_figure.savefig(buf)
QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
buf.close()
def callback_save_image(self):
response=save_as_filter(self,"png (*.png);;jpg (*.jpg)")
if response != None:
print(response)
self.my_figure.savefig(response)
def set_data_file(self,file):
self.optical_mode_file=os.path.join(os.getcwd(),"light_dump",file)
def draw_graph(self):
self.layer_end=[]
self.layer_name=[]
n=0
self.my_figure.clf()
ax1 = self.my_figure.add_subplot(111)
ax2 = ax1.twinx()
x_pos=0.0
layer=0
color =['r','g','b','y','o','r','g','b','y','o']
start=0.0
for i in range(0,epitaxy_get_layers()):
if epitaxy_get_electrical_layer(i).startswith("dos")==False:
start=start-epitaxy_get_width(i)
else:
break
print("START=",start)
start=start*1e9
x_pos=start
for i in range(0,epitaxy_get_layers()):
# label=epitaxy_get_mat_file(i)
layer_ticknes=epitaxy_get_width(i)
layer_material=epitaxy_get_mat_file(i)
delta=float(layer_ticknes)*1e9
print(epitaxy_get_electrical_layer(i))
if epitaxy_get_electrical_layer(i).startswith("dos")==False:
mat_file=os.path.join(os.getcwd(),'materials',layer_material,'mat.inp')
myfile = open(mat_file)
self.mat_file_lines = myfile.readlines()
myfile.close()
#.........这里部分代码省略.........
示例15: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setFocusPolicy [as 别名]
class Window(QDialog):
def __init__(self, params_object, library_object, compound_list, mixture_id, parent=None):
QDialog.__init__(self, parent)
matplotlib.projections.register_projection(My_Axes)
self.library = library_object
self.params = params_object
self.compounds = list(compound_list)
self.mixture_id = mixture_id
self.show_list = list(compound_list)
self.compound_colors_list = ['red', 'blue', 'green', 'orange', 'purple', 'teal', 'pink', 'gray',
'cyan', 'magenta', 'gold', 'brown', 'olive', 'yellow', 'maroon',
'darkseagreen', 'darksalmon', 'turquoise', 'khaki', 'crimson']
self.compound_colors = self.compound_colors_list * ((len(self.show_list) // 20) + 1)
self.scale = 1.05
self.show_rois = True
self.show_full_rois = False
self.show_ignored = False
self.show_ignored_peaks = False
self.show_positive_overlap = False
self.setWindowTitle("NMRmix: Simulated Spectra of Mixture %s" % self.mixture_id)
self.createMainFrame()
self.drawData()
def createMainFrame(self):
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.fig.set_size_inches(12, 5)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
self.showroisCheckBox = QCheckBox("Show Unoverlapped ROIs")
self.showroisCheckBox.setStyleSheet('QCheckBox{font-size: 12px;}')
self.showroisCheckBox.setToolTip("Shows the regions of interest around every non-overlapped peak.\n"
"Useful for visualizing the regions that should be monitored in this mixture.")
self.showroisCheckBox.setChecked(True)
self.showfullroisCheckBox = QCheckBox("Show Complete ROIs")
self.showfullroisCheckBox.setStyleSheet('QCheckBox{font-size: 12px;}')
self.showfullroisCheckBox.setToolTip("Shows the regions of interest around every peak regardless of whether\n"
"it is overlapped or not. Useful for visualizing the magnitude of overlaps.")
self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
self.showignoredregionsCheckBox.setStyleSheet('QCheckBox{font-size: 12px;}')
self.showignoredregionsCheckBox.setToolTip("Shows the ranges set by the solvent/buffer ignore regions, if any.")
self.showignoredpeaksCheckBox = QCheckBox("Show Ignored Peaks")
self.showignoredpeaksCheckBox.setStyleSheet('QCheckBox{font-size: 12px;}')
self.showignoredpeaksCheckBox.setToolTip("Shows any compound peaks that are in the solvent/buffer ignore regions, if any.\n"
"These peaks are ignored and are not evaluated during mixing.")
self.showpositiveoverlapCheckBox = QCheckBox("Show Overlaps as Positive")
self.showpositiveoverlapCheckBox.setStyleSheet('QCheckBox{font-size: 12px;}')
self.showpositiveoverlapCheckBox.setToolTip("By default, peaks that overlap are shown as negative peaks.\n"
"This option allows for these peaks to be shown as positive peaks.")
self.resetButton = QPushButton("Reset")
self.resetButton.setStyleSheet("QPushButton{color: orange; font-weight: bold;}")
self.resetButton.setToolTip("Resets the spectrum to the default view.")
self.saveButton = QPushButton("Save")
self.saveButton.setStyleSheet("QPushButton{color: green; font-weight: bold;}")
self.saveButton.setToolTip("Saves the image in the spectrum window.")
self.closeButton = QPushButton("Close")
self.closeButton.setStyleSheet("QPushButton{color: red; font-weight: bold;}")
self.closeButton.setToolTip("Closes this window.")
vbox = QVBoxLayout(self)
self.spectraLabel = QLabel("Simulated Spectra of Mixture %s" % self.mixture_id)
self.spectraLabel.setStyleSheet('QLabel{color: red; font-weight: bold; qproperty-alignment: AlignCenter; '
'font-size: 14px;}')
self.spectraLabel.setToolTip("Shows the simulated spectra of the compounds in this mixture based solely on peaklists.\n"
"Peaks are drawn based on a Lorentzian shape.")
vbox.addWidget(self.spectraLabel)
vbox.addWidget(self.canvas)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis / Scroll-wheel to change intensity scale"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 12px;}')
vbox.addWidget(self.instructionLabel)
gridbox = QGridLayout()
self.compound_legend = {}
for i, compound in enumerate(self.show_list):
self.compound_legend[i] = QPushButtonRight(str(compound))
self.compound_legend[i].setStyleSheet("QPushButton {background-color: %s; font-weight: bold;}" % self.compound_colors[i])
self.compound_legend[i].leftClicked.connect(self.handleLegend)
self.compound_legend[i].rightClicked.connect(self.handleCompoundButtonRight)
self.compound_legend[i].setToolTip("Left-click to toggle the spectra for this compound.\n"
"Right-click to show compound infomation.")
row = int(i / 6)
column = i % 6
gridbox.addWidget(self.compound_legend[i], row, column)
vbox.addLayout(gridbox)
hbox1 = QHBoxLayout()
hbox1.addWidget(self.showroisCheckBox)
hbox1.addWidget(self.showfullroisCheckBox)
hbox1.addWidget(self.showignoredregionsCheckBox)
hbox1.addWidget(self.showignoredpeaksCheckBox)
hbox1.addWidget(self.showpositiveoverlapCheckBox)
#.........这里部分代码省略.........