def saveImage(self): file_name = QtWidgets.QFileDialog().getSaveFileName(self, "Save Image", 'multicolor_image.png', 'PNG(*.png);; TIFF(*.tiff);; JPG(*.jpg)') exporter = pg.exporters.ImageExporter(self.canvas.getViewBox()) exporter.export(file_name[0])
def __init__(self, data, parent=None): super().__init__(parent) # Layout management self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.setObjectName('Main layout') self.header_layout = QtWidgets.QHBoxLayout() self.header_layout.setObjectName('Header layout') self.cmap_norm_layout = QtWidgets.QHBoxLayout() self.cmap_norm_layout.setObjectName('CMap Normalization layout') self.gamma_layout = QtWidgets.QVBoxLayout() self.gamma_layout.setObjectName('Gamma layout') self.gamma_value_layout = QtWidgets.QHBoxLayout() self.piecewise_layout = QtWidgets.QVBoxLayout() self.cmap_layout = QtWidgets.QVBoxLayout() self.bottom_layout = QtWidgets.QHBoxLayout() # Create widgets self.power_law_radio = QtWidgets.QRadioButton('Power Law') self.power_law_radio.setChecked(True) self.piecewise_radio = QtWidgets.QRadioButton('Piecewise') self.piecewise_reset = QtWidgets.QPushButton('Reset') self.piecewise_reset.setDisabled(True) self.norm_button_group = QtWidgets.QButtonGroup() self.norm_button_group.addButton(self.power_law_radio) self.norm_button_group.addButton(self.piecewise_radio) self.gamma_label = QtWidgets.QLabel('Gamma') self.gamma_spinbox = QtWidgets.QDoubleSpinBox() self.gamma_spinbox.setMinimumSize(50, 0) self.gamma_spinbox.setRange(10**-2, 10**2) self.gamma_spinbox.setValue(1) self.gamma_spinbox.setSingleStep(0.1) self.gamma_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.gamma_slider.setTickPosition(QtWidgets.QSlider.TicksBelow) gamma_min = -20 gamma_max = 20 gamma_step = 1 self.gamma_slider.setMinimum(gamma_min) self.gamma_slider.setMaximum(gamma_max) self.gamma_slider.setValue(0) self.enable_isocurve_layout = QtWidgets.QHBoxLayout() self.enable_isocurve_checkbox = QtWidgets.QCheckBox() self.enable_isocurve_checkbox.setChecked(True) self.enable_isocurve = True self.enable_isocurve_label = QtWidgets.QLabel('Enable Isocurve?') self.cmap_label = QtWidgets.QLabel('Colormap') self.cmap_label.setAlignment(QtCore.Qt.AlignHCenter) self.cmap_combobox = QtWidgets.QComboBox() self.cmap_combobox.setMinimumSize(150, 0) self.header = QtWidgets.QWidget() self.header.setLayout(self.header_layout) self.splitter = QtWidgets.QSplitter() self.splitter.setOrientation(QtCore.Qt.Vertical) self.pg_win = PGCMapEditor(data) self.pg_widget = QtWidgets.QWidget() self.pg_widget.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.pg_win) self.pg_widget.setLayout(layout) self.save_map_button = QtWidgets.QPushButton('Save Color Map') self.load_map_button = QtWidgets.QPushButton('Load Color Map') self.ok_button = QtWidgets.QPushButton('OK') self.cancel_button = QtWidgets.QPushButton('Cancel') # Populate the combo box self.cmap_combobox.setInsertPolicy( QtWidgets.QComboBox.InsertAlphabetically) for cmap in CMap().cmaps: self.cmap_combobox.addItem(CMap().load_icon(cmap), cmap) # for filename in os.listdir('cmaps'): # if fnmatch.fnmatch(filename, '*.npy'): # cmap_name = os.path.splitext(filename)[0] # self.cmap_combobox.addItem(QtGui.QIcon('cmaps' + os.sep + cmap_name + '.jpg'), cmap_name) self.cmap_combobox.setIconSize(QtCore.QSize(64, 12)) self.cmap_combobox.setCurrentText('blue_orange') def update_cmap(cmap_name): self.pg_win.load_ct(cmap_name) self.pg_win.update() self.cmap_combobox.currentTextChanged.connect(update_cmap) # Connect signals to slots self.gamma_slider.valueChanged.connect(self.gamma_spinbox_slot) self.gamma_spinbox.valueChanged.connect(self.gamma_slider_slot) self.piecewise_radio.clicked.connect(self.piecewise_clicked) self.power_law_radio.clicked.connect(self.power_law_clicked) self.enable_isocurve_checkbox.clicked.connect( self.enable_isocurve_clicked) self.piecewise_reset.clicked.connect(self.reset_clicked) self.save_map_button.clicked.connect(self.save_cmap_clicked) self.load_map_button.clicked.connect(self.load_cmap_clicked) # Initialize update_cmap('blue_orange') # Add widgets self.header_layout.addLayout(self.cmap_norm_layout) self.cmap_norm_layout.addLayout(self.gamma_layout) self.gamma_layout.addWidget(self.power_law_radio) self.gamma_layout.addLayout(self.gamma_value_layout) self.gamma_value_layout.addWidget(self.gamma_label) self.gamma_value_layout.addWidget(self.gamma_spinbox) self.gamma_value_layout.addWidget(self.gamma_slider) self.enable_isocurve_layout.addWidget(self.enable_isocurve_checkbox) self.enable_isocurve_layout.addWidget(self.enable_isocurve_label) self.enable_isocurve_layout.addStretch(0) self.gamma_layout.addLayout(self.enable_isocurve_layout) self.cmap_norm_layout.addLayout(self.piecewise_layout) self.piecewise_layout.addWidget(self.piecewise_radio) self.piecewise_layout.addWidget(self.piecewise_reset) self.header_layout.addLayout(self.cmap_layout) self.cmap_layout.addWidget(self.cmap_label) self.cmap_layout.addWidget(self.cmap_combobox) self.splitter.addWidget(self.header) self.splitter.addWidget(self.pg_widget) self.splitter.setStretchFactor( 0, 1) # resizes the pg.GraphicsLayoutWidget against the header # -- makes a visible line and adds the splitter handle to a QFrame widget which draws a relief line splitter_handle = self.splitter.handle(1) layout = QtWidgets.QVBoxLayout(splitter_handle) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) line = QtWidgets.QFrame(splitter_handle) line.setFrameShape(QtWidgets.QFrame.HLine) line.setFrameShadow(QtWidgets.QFrame.Sunken) layout.addWidget(line) # -- end self.main_layout.addWidget(self.splitter) self.main_layout.addLayout(self.bottom_layout) self.bottom_layout.addWidget(self.save_map_button) self.bottom_layout.addWidget(self.load_map_button) self.bottom_layout.addStretch(0) self.bottom_layout.addWidget(self.ok_button) self.bottom_layout.addWidget(self.cancel_button) self.setLayout(self.main_layout)
else: pass def importState(self): file_name = QtWidgets.QFileDialog().getOpenFileName(self, "Open a State File", '', 'json file(*json)') if file_name[0]: with open(file_name[0], 'r') as fp: self.image_dict = json.load(fp) self.createMultiColorView(self.image_dict) self.displayImageNames(self.image_dict) else: pass def saveImage(self): file_name = QtWidgets.QFileDialog().getSaveFileName(self, "Save Image", 'multicolor_image.png', 'PNG(*.png);; TIFF(*.tiff);; JPG(*.jpg)') exporter = pg.exporters.ImageExporter(self.canvas.getViewBox()) exporter.export(file_name[0]) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = MultiChannelWindow() window.show() sys.exit(app.exec_())
def __init__(self): # Simple reason why we use it here is that it allows us to # access variables, methods etc in the design.py file super(self.__class__, self).__init__() self.setupUi(self) # This is defined in design.py file automatically # It sets up layout and widgets that are defined self.setWindowTitle(self.app_name) self.mainToolBar = QtWidgets.QToolBar(self) self.mainToolBar.setObjectName("mainToolBar") self.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.save_action = self.mainToolBar.addAction("Save settings") self.save_icon = QtGui.QIcon() self.save_icon.addPixmap(QtGui.QPixmap(ICON_SAVE_PATH)) self.save_action.setIcon(self.save_icon) self.restoreDefault_action = self.mainToolBar.addAction( "Restore to default settings") self.restore_icon = QtGui.QIcon() self.restore_icon.addPixmap(QtGui.QPixmap(ICON_OPEN_PATH)) self.restoreDefault_action.setIcon(self.restore_icon) self.settings_dict = self.open_json("settings/custom_settings.json") self.a_gb_dict = { } #dict that contains a group box for each settings item # elf.gridLayout_2.addWidget(self.groupBox, 1, 2, 1, 1) row = 2 for key in self.settings_dict: print(key) self.a_gb_dict[key] = {} self.a_gb_dict[key]["groupBox"] = QtWidgets.QGroupBox( self.scrollArea) # self.a_gb_dict[key]["groupBox"].setGeometry(QtCore.QRect(20, 20, 571, 223)) self.a_gb_dict[key]["groupBox"].setTitle(key) self.a_gb_dict[key]["gb_layout"] = QtWidgets.QGridLayout( self.a_gb_dict[key]["groupBox"]) self.a_gb_dict[key]["layout"] = QtWidgets.QGridLayout() self.a_gb_dict[key]["name_label"] = QtWidgets.QLabel( self.a_gb_dict[key]["groupBox"]) self.a_gb_dict[key]["name_label"].setText("Name") self.a_gb_dict[key]["layout"].addWidget( self.a_gb_dict[key]["name_label"], 0, 0, 1, 1) self.a_gb_dict[key]["min_label"] = QtWidgets.QLabel( self.a_gb_dict[key]["groupBox"]) self.a_gb_dict[key]["min_label"].setText("Minimum") self.a_gb_dict[key]["layout"].addWidget( self.a_gb_dict[key]["min_label"], 0, 1, 1, 1) self.a_gb_dict[key]["max_label"] = QtWidgets.QLabel( self.a_gb_dict[key]["groupBox"]) self.a_gb_dict[key]["max_label"].setText("Maximum") self.a_gb_dict[key]["layout"].addWidget( self.a_gb_dict[key]["max_label"], 0, 2, 1, 1) self.a_gb_dict[key]["ss_label"] = QtWidgets.QLabel( self.a_gb_dict[key]["groupBox"]) self.a_gb_dict[key]["ss_label"].setText("Single Step") self.a_gb_dict[key]["layout"].addWidget( self.a_gb_dict[key]["ss_label"], 0, 3, 1, 1) self.a_gb_dict[key]["item_list"] = [] test_n = 1 #self.settings_dict["odrive_config"][key].index(list_item) for list_item in self.settings_dict[key]: item_dict = {} item_dict["name"] = QtWidgets.QLabel( self.a_gb_dict[key]["groupBox"]) item_dict["name"].setText(list_item["name"]) self.a_gb_dict[key]["layout"].addWidget( item_dict["name"], test_n, 0, 1, 1) if list_item["type"] == "float": item_dict["min"] = QtWidgets.QDoubleSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["min"].setDecimals(list_item["decimals"]) else: item_dict["min"] = QtWidgets.QSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["min"].setMaximum(list_item["max"]) item_dict["min"].setMinimum(list_item["min"]) item_dict["min"].setSingleStep(list_item["step"]) item_dict["min"].setValue(list_item["slider_min"]) self.a_gb_dict[key]["layout"].addWidget( item_dict["min"], test_n, 1, 1, 1) if list_item["type"] == "float": item_dict["max"] = QtWidgets.QDoubleSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["max"].setDecimals(list_item["decimals"]) else: item_dict["max"] = QtWidgets.QSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["max"].setMaximum(list_item["max"]) item_dict["max"].setMinimum(list_item["min"]) item_dict["max"].setSingleStep(list_item["step"]) item_dict["max"].setValue(list_item["slider_max"]) self.a_gb_dict[key]["layout"].addWidget( item_dict["max"], test_n, 2, 1, 1) if list_item["type"] == "float": item_dict["step"] = QtWidgets.QDoubleSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["step"].setDecimals(list_item["decimals"]) else: item_dict["step"] = QtWidgets.QSpinBox( self.a_gb_dict[key]["groupBox"]) item_dict["step"].setMaximum(list_item["max"]) item_dict["step"].setMinimum(list_item["min"]) item_dict["step"].setSingleStep(list_item["step"]) item_dict["step"].setValue(list_item["slider_step"]) self.a_gb_dict[key]["layout"].addWidget( item_dict["step"], test_n, 3, 1, 1) self.a_gb_dict[key]["item_list"].append(item_dict) test_n += 1 self.a_gb_dict[key]["gb_layout"].addLayout( self.a_gb_dict[key]["layout"], 0, 0, 1, 1) self.gridLayout_3.addWidget(self.a_gb_dict[key]["groupBox"], row, 0, 1, 1) row += 1
def __init__(self): if not os.path.exists(FractalGUI.def_path): os.mkdir(FractalGUI.def_path) # Create workers for image saving mp.set_start_method("spawn") self.__save_queue = mp.JoinableQueue() self.__save_pool = mp.Pool(initializer=save_process, initargs=(self.__save_queue,)) # Initialise PyQtGraph app = pg.mkQApp() pg.setConfigOptions(antialias=True) win = QtWidgets.QMainWindow() win.resize(1200, 700) # Couldn't get multiprocess graphics rendering to work # graphics_view = pyqtgraph.widgets.RemoteGraphicsView.RemoteGraphicsView() # useOpenGL=True speeds the rendering # self.__imv = pg.ImageView(view=graphics_view) self.__imv = pg.ImageView() win.setCentralWidget(self.__imv) win.setWindowTitle("Fractal view") self.__imv.getView().invertY(False) # Disable the default y axis inversion win2 = QtWidgets.QWidget() win2.setWindowTitle("Fractal controls") win2_layout = QtWidgets.QGridLayout() win2.setLayout(win2_layout) labels = [ "fractal", "x resolution", "y resolution", "x min", "x max", "y min", "y max", "c real", "c imag", "iterations" ] for i, text in enumerate(labels): frame_label = QtWidgets.QLabel() frame_label.setText(text) win2_layout.addWidget(frame_label, i, 0) self.__res_x = FractalGUI.def_res_x self.__res_y = FractalGUI.def_res_y self.__x_min = FractalGUI.def_x_min self.__x_max = FractalGUI.def_x_max self.__y_min = FractalGUI.def_y_min self.__y_max = FractalGUI.def_y_max self.__c_real = FractalGUI.def_c_real self.__c_imag = FractalGUI.def_c_imag self.__iter_max = FractalGUI.def_iter self.__start_x_min = None self.__start_x_max = None self.__start_y_min = None self.__start_y_max = None self.__start_c_real = None self.__start_c_imag = None self.__start_iter_max = None self.__end_x_min = None self.__end_x_max = None self.__end_y_min = None self.__end_y_max = None self.__end_c_real = None self.__end_c_imag = None self.__end_iter_max = None self.__image: np.ndarray = None self.__input_frac = QtWidgets.QComboBox() self.__input_frac.addItem("Mandelbrot colored", "mandel-color") self.__input_frac.addItem("Mandelbrot grayscale", "mandel") self.__input_frac.addItem("Julia colored", "julia-color") self.__input_frac.addItem("Julia grayscale", "julia") # This works but would require different parameter entries in the GUI # self.__input_frac.addItem("Sierpinski carpet", "carpet") win2_layout.addWidget(self.__input_frac, 0, 1) self.__input_res_x = pg.SpinBox(value=self.__res_x, int=True, dec=True, minStep=1, step=1, min=10) self.__input_res_y = pg.SpinBox(value=self.__res_y, int=True, dec=True, minStep=1, step=1, min=10) win2_layout.addWidget(self.__input_res_x, 1, 1) win2_layout.addWidget(self.__input_res_y, 2, 1) self.__input_x_min = pg.SpinBox(value=self.__x_min, dec=True) self.__input_x_max = pg.SpinBox(value=self.__x_max, dec=True) self.__input_y_min = pg.SpinBox(value=self.__y_min, dec=True) self.__input_y_max = pg.SpinBox(value=self.__y_max, dec=True) win2_layout.addWidget(self.__input_x_min, 3, 1) win2_layout.addWidget(self.__input_x_max, 4, 1) win2_layout.addWidget(self.__input_y_min, 5, 1) win2_layout.addWidget(self.__input_y_max, 6, 1) self.__input_c_real = pg.SpinBox(value=self.__c_real, dec=True, minStep=0) self.__input_c_imag = pg.SpinBox(value=self.__c_imag, dec=True, minStep=0) win2_layout.addWidget(self.__input_c_real, 7, 1) win2_layout.addWidget(self.__input_c_imag, 8, 1) self.__input_iter = pg.SpinBox(value=self.__iter_max, int=True, dec=True, min=1) win2_layout.addWidget(self.__input_iter, 9, 1) self.__renderButton = QtWidgets.QPushButton("Render") win2_layout.addWidget(self.__renderButton, 10, 1) self.__renderButton.clicked.connect(self.render) self.__zoomButton = QtWidgets.QPushButton("Zoom") win2_layout.addWidget(self.__zoomButton, 11, 1) self.__zoomButton.clicked.connect(self.zoom) self.__saveButton = QtWidgets.QPushButton("Save") win2_layout.addWidget(self.__saveButton, 12, 1) self.__saveButton.clicked.connect(self.save) self.__resetButton = QtWidgets.QPushButton("Reset") win2_layout.addWidget(self.__resetButton, 13, 1) self.__resetButton.clicked.connect(self.reset) frame_label = QtWidgets.QLabel() frame_label.setText("frames") win2_layout.addWidget(frame_label, 0, 2) fps_label = QtWidgets.QLabel() fps_label.setText("FPS") win2_layout.addWidget(fps_label, 1, 2) self.__input_frames = pg.SpinBox(value=FractalGUI.def_frames, dec=True, int=True, minStep=1, step=1, min=1) win2_layout.addWidget(self.__input_frames, 0, 3) self.__input_fps = pg.SpinBox(value=FractalGUI.def_fps, dec=True, int=True, minStep=1, step=1, min=1) win2_layout.addWidget(self.__input_fps, 1, 3) self.__startButton = QtWidgets.QPushButton("Set start frame") self.__endButton = QtWidgets.QPushButton("Set end frame") win2_layout.addWidget(self.__startButton, 2, 2) win2_layout.addWidget(self.__endButton, 2, 3) self.__startButton.clicked.connect(self.set_start) self.__endButton.clicked.connect(self.set_end) self.__animeButton = QtWidgets.QPushButton("Render animation") self.__animeButton.clicked.connect(self.animate) win2_layout.addWidget(self.__animeButton, 3, 2) # self.__testButton = QtWidgets.QPushButton("Test") # self.__testButton.clicked.connect(self.test) # win2_layout.addWidget(self.__testButton, 3, 3) self.__renderLabel = QtWidgets.QLabel() self.__renderLabel.setText("") win2_layout.addWidget(self.__renderLabel, 4, 2) win.show() win2.show() self.render() # Note: PyQtGraph is prone to crashing on exit # (mysterious segfaults etc., especially when used along with other libraries) # This is not caused by improper usage but bugs in the library itself # Please see this for documentation: # http://www.pyqtgraph.org/documentation/functions.html#pyqtgraph.exit app.exec_()
def __init__(self, broker_addr="", profile_addr="", graph_name="graph", loop=None): super().__init__() if loop is None: self.app = QtGui.QApplication([]) loop = QEventLoop(self.app) asyncio.set_event_loop(loop) self.ctx = zmq.asyncio.Context() if broker_addr: self.broker = self.ctx.socket(zmq.SUB) self.broker.setsockopt_string(zmq.SUBSCRIBE, 'profiler') self.broker.connect(broker_addr) else: self.broker = None self.graph_name = graph_name self.profile_addr = profile_addr self.profile = self.ctx.socket(zmq.SUB) self.profile.setsockopt_string(zmq.SUBSCRIBE, self.graph_name) self.task = None self.deserializer = Deserializer() self.current_version = 0 self.metadata = {} # {version : metadata} self.parents = set() self.heartbeat_data = {} self.widget = QtWidgets.QWidget() self.layout = QtGui.QGridLayout(self.widget) self.widget.setLayout(self.layout) self.enabled_nodes = {} self.trace_layout = QtGui.QFormLayout(self.widget) hbox = QtWidgets.QHBoxLayout(self.widget) selectAll = QtWidgets.QPushButton("Select All", self.widget) selectAll.clicked.connect(self.selectAll) unselectAll = QtWidgets.QPushButton("Unselect All", self.widget) unselectAll.clicked.connect(self.unselectAll) hbox.addWidget(selectAll) hbox.addWidget(unselectAll) self.trace_layout.addRow(hbox) self.trace_group = WidgetGroup() self.trace_group.sigChanged.connect(self.state_changed) self.layout.addLayout(self.trace_layout, 0, 0, -1, 1) self.graphicsLayoutWidget = pg.GraphicsLayoutWidget() self.layout.addWidget(self.graphicsLayoutWidget, 0, 1, -1, -1) self.time_per_heartbeat = self.graphicsLayoutWidget.addPlot(row=0, col=0) self.time_per_heartbeat.showGrid(True, True) self.time_per_heartbeat.setLabel('bottom', "Heartbeat") self.time_per_heartbeat.setLabel('left', "Time (Sec)") self.time_per_heartbeat_data = collections.defaultdict( lambda: np.array([np.nan] * 100)) self.time_per_heartbeat_traces = {} self.time_per_heartbeat_legend = self.time_per_heartbeat.addLegend() self.heartbeats_per_second = self.graphicsLayoutWidget.addPlot(row=0, col=1) self.heartbeats_per_second.showGrid(True, True) self.heartbeats_per_second.setLabel('bottom', "Heartbeat") self.heartbeats_per_second.setLabel('left', "Heartbeats/Second") self.heartbeats_per_second_data = np.array([np.nan] * 100) self.heartbeats_per_second_trace = None self.percent_per_heartbeat = self.graphicsLayoutWidget.addPlot( row=1, col=0, rowspan=1, colspan=2) self.percent_per_heartbeat.showGrid(True, True) self.percent_per_heartbeat_trace = None self.last_updated = pg.LabelItem( parent=self.time_per_heartbeat.getViewBox()) self.total_heartbeat_time = pg.LabelItem( parent=self.percent_per_heartbeat.getViewBox()) self.heartbeat_per_second = pg.LabelItem( parent=self.heartbeats_per_second.getViewBox()) self.win = ProfilerWindow(self) self.win.setWindowTitle('Profiler') self.win.setCentralWidget(self.widget) self.win.show() with loop: loop.run_until_complete( asyncio.gather(self.process_broker_message(), self.monitor()))
# -*- coding: utf-8 -*- """ Use a HistogramLUTWidget to control the contrast / coloration of an image. """ ## Add path to library (just for examples; you do not need this) import initExample import numpy as np from pyqtgraph.Qt import QtGui, QtCore, QtWidgets import pyqtgraph as pg app = QtWidgets.QApplication([]) win = QtWidgets.QMainWindow() win.resize(800, 600) win.show() win.setWindowTitle('pyqtgraph example: Histogram LUT') cw = QtWidgets.QWidget() win.setCentralWidget(cw) l = QtWidgets.QGridLayout() cw.setLayout(l) l.setSpacing(0) v = pg.GraphicsView() vb = pg.ViewBox() vb.setAspectLocked() v.setCentralItem(vb) l.addWidget(v, 0, 0)
def __init__(self, parent = None, *args, data_path = False, project_path, selection = False): QtWidgets.QWidget.__init__(self, parent, *args) self.ui = Ui_Form() self.ui.setupUi(self) self.setWindowTitle("CenterFinder") self.setWindowIcon(QtGui.QIcon("icons/centerfinder.png")) self.ui.graphicsView.ui.menuBtn.hide() self.ui.graphicsView.ui.roiBtn.hide() # self.ui.graphicsView.ui.histogram.hide() self.ui.pushButtonOverwrite.setEnabled(True) self.show() self.ui.pushButtonOverwrite.clicked.connect(self.overwrite_center) self.ui.checkBoxOverwrite.clicked.connect(self.toggle_overwrite) self.overwrite = False self.data_path = data_path if self.data_path == False: self.data_path = QtWidgets.QFileDialog.getExistingDirectory(caption = "Select directory or drive that contains the video files you are working with") self.all_videos = [os.path.join(root, f) for root, dirs, files in os.walk(self.data_path) for f in files if ".avi" in f] self.project_path = project_path self.vid_dict = {} self.videos_not_found = [] self.selection = selection for selected in self.selection: try: vid = [x for x in self.all_videos if selected.text(0) in x] self.vid_dict[selected.text(0)] = vid[0] except: self.videos_not_found.append(selected) if len(self.videos_not_found) > 0: QtWidgets.QMessageBox.warning(self, "Videos Not Found", str(len(self.videos_not_found))+" out of "+ str(len(self.selection)) +" not found in selected path") for vid in self.videos_not_found: self.selection.remove(vid) self.ui.comboBoxThresholdMethod.addItem("NONE") self.ui.comboBoxThresholdMethod.addItem("BINARY") self.ui.comboBoxThresholdMethod.addItem("TOZERO") self.ui.comboBoxThresholdMethod.currentTextChanged.connect(self.check_thresholding_method) self.ui.comboBoxThresholdMethod.currentIndexChanged.connect(self.process_item) self.ui.pushButtonRedoCenter.clicked.connect(self.process_item) self.ui.listWidgetVideos.itemSelectionChanged.connect(self.process_item) self.ui.listWidgetVideos.itemDoubleClicked.connect(self.process_item) self.ui.pushButtonStartStop.clicked.connect(self.start_stop) self.check_thresholding_method(self.ui.comboBoxThresholdMethod.currentText()) self.counter = 0 self.ui.listWidgetVideos.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.ui.listWidgetVideos.customContextMenuRequested.connect(self.contextMenuEvent_listwidgetVideos) self.flag_dataKeepaction = QtWidgets.QAction("&Flag and keep center", self, triggered = lambda: self.flag_data(delete = False)) self.flag_dataDeleteaction = QtWidgets.QAction("&Flag and delete center", self, triggered = lambda: self.flag_data(delete = True)) for item in self.selection: to_add = QtGui.QListWidgetItem(item.text(0)) to_add.setData(1,item.text(1)) if "center.txt" in os.listdir(item.text(1)): to_add.setBackground(QtGui.QColor("lightblue")) self.ui.listWidgetVideos.addItem(to_add)
widgets["spectrumPlot"].setLabel("bottom", "Frequency", units="Hz") widgets["spectrumPlot"].setXRange(100, 4000) widgets["spectrumPlot"].setYRange(-100, -20) widgets["spectrumPlot"].setLimits(xMin=100, xMax=4000, yMin=-120, yMax=0) widgets["spectrumPlot"].showGrid(True, True) widgets["estimatorRange"] = pg.LinearRegionItem([100,3000]) widgets["estimatorRange"].setBounds([100,4000]) d1.addWidget(widgets["spectrumPlot"]) widgets["spectrumPlotRange"] = [-100, -20] w3_stats = pg.LayoutWidget() widgets["snrBar"] = QtWidgets.QProgressBar() widgets["snrBar"].setOrientation(QtCore.Qt.Vertical) widgets["snrBar"].setRange(-10, 15) widgets["snrBar"].setValue(-10) widgets["snrBar"].setTextVisible(False) widgets["snrBar"].setAlignment(QtCore.Qt.AlignCenter) widgets["snrLabel"] = QtGui.QLabel("--.-") widgets["snrLabel"].setAlignment(QtCore.Qt.AlignCenter); widgets["snrLabel"].setFont(QtGui.QFont("Courier New", 14)) w3_stats.addWidget(widgets["snrBar"], 0, 1, 1, 1) w3_stats.addWidget(widgets["snrLabel"], 1, 0, 1, 3) w3_stats.layout.setColumnStretch(0, 2) w3_stats.layout.setColumnStretch(2, 2) d2_stats.addWidget(w3_stats)
def appendUser(self): n = QtWidgets.QLabel("No status!") self.mainToolBar.addWidget(n) return n
def contextMenuEvent_listwidgetVideos(self, event): menu = QtWidgets.QMenu(self) menu.addAction(self.flag_dataDeleteaction) menu.addAction(self.flag_dataKeepaction) menu.popup(self.ui.listWidgetVideos.mapToGlobal(event))
def __init__(self, display = None): super(NodeWidget, self).__init__() self.display = display self.hLayout = QtWidgets.QHBoxLayout() self.vLayout = QtWidgets.QVBoxLayout() self.btnLayout = QtWidgets.QGridLayout() self.sliderLayout = QtWidgets.QGridLayout() self.setLayout(self.hLayout) # self.layout.setAlignment(pg.QtCore.Qt.AlignCenter) #Create button and sliders self.btnUp = QtWidgets.QPushButton("Up") self.btnDown = QtWidgets.QPushButton("Down") self.btnSetMaxPos = QtWidgets.QPushButton("Set Max Pos") self.btnSetMinPos = QtWidgets.QPushButton("Set Min Pos") self.btnCalibrate = QtWidgets.QPushButton("Calibrate") self.btnShowHidePlot = QtWidgets.QPushButton("Plot") self.btnLive = QtWidgets.QPushButton("Live On") self.btnReset = QtWidgets.QPushButton("Reset") self.btnTimerOff = QtWidgets.QPushButton("TimerOff") self.btnDisconnect = QtWidgets.QPushButton("Disconnect") self.btnSchedulerDemo = QtWidgets.QPushButton("Scheduler Demo") self.btnStop = QtWidgets.QPushButton("Stop") self.paramStep = Param(name='Step', defaultValue='200') self.paramKp = Param(name='Kp', defaultValue='0.3') self.state = State() self.sliderPos = SliderWidget(min=0, max=100, interval=30, orientation=Qt.Vertical, name='P') self.sliderLight = SliderWidget(min=0, max=100, interval=40, orientation=Qt.Vertical, name='L') self.plot = DynamicPlotWidget(sampleinterval=0.05, timewindow=10.) # self.plot.hide() # self.layout.addWidget(widget, row, column, rowSpan, columnSpan) self.btnLayout.addWidget(self.btnUp, 1, 1) self.btnLayout.addWidget(self.btnDown, 2, 1) self.btnLayout.addWidget(self.btnCalibrate, 3, 1) self.btnLayout.addWidget(self.btnLive, 4, 1) self.btnLayout.addWidget(self.btnSetMaxPos, 1, 2) self.btnLayout.addWidget(self.btnSetMinPos, 2, 2) self.btnLayout.addWidget(self.btnShowHidePlot, 3, 2) self.btnLayout.addWidget(self.btnReset, 4, 2) self.btnLayout.addWidget(self.btnTimerOff, 5, 1) self.btnLayout.addWidget(self.btnDisconnect, 5, 2) self.btnLayout.addWidget(self.btnSchedulerDemo, 6, 1) self.btnLayout.addWidget(self.btnStop, 6, 2) self.btnLayout.addWidget(self.paramStep, 7, 1) self.btnLayout.addWidget(self.paramKp, 7, 2) self.btnLayout.addWidget(self.state, 8, 1, 1, 2) self.sliderLayout.addWidget(self.sliderPos, 1, 1) self.sliderLayout.addWidget(self.sliderLight, 1, 2) self.vLayout.addLayout(self.btnLayout) self.vLayout.addLayout(self.sliderLayout) self.hLayout.addWidget(self.plot) self.hLayout.addLayout(self.vLayout)
ViewBox is the general-purpose graphical container that allows the user to zoom / pan to inspect any area of a 2D coordinate system. This unimaginative example demonstrates the construction of a ViewBox-based plot area with axes, very similar to the way PlotItem is built. """ ## This example uses a ViewBox to create a PlotWidget-like interface import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtWidgets app = pg.mkQApp("ViewBox Example") mw = QtWidgets.QMainWindow() mw.setWindowTitle('pyqtgraph example: ViewBox') mw.show() mw.resize(800, 600) gv = pg.GraphicsView() mw.setCentralWidget(gv) l = QtWidgets.QGraphicsGridLayout() l.setHorizontalSpacing(0) l.setVerticalSpacing(0) vb = pg.ViewBox() p1 = pg.PlotDataItem() vb.addItem(p1)
def __init__(self, model, parent=None): super(SoundEffectorView, self).__init__(parent) """ Model """ self.model = model """ Data """ self.freq = np.linspace(0, 44100, self.model.ANALYZEDSIZE) self.plotdata = np.zeros(self.model.CHUNK) self.update_msec = 10 """ Window """ self.setWindowTitle("test") """ Label Widget """ self.label = QtGui.QLabel("SoundEffector") """ Effect Switch Widget """ self.pre_booster_switch = QtWidgets.QCheckBox("PER-BOOSTER", self) self.pre_booster_bar = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.pre_booster_bar.setMinimum(1) self.pre_booster_bar.setMaximum(10) self.distortion_switch = QtWidgets.QCheckBox("DISTORTION", self) self.distortion_bar = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.distortion_bar.setMinimum(10) self.distortion_bar.setMaximum(50) self.phaser_switch = QtWidgets.QCheckBox("PHASER", self) self.post_booster_switch = QtWidgets.QCheckBox("POST-BOOSTER", self) self.post_booster_bar = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.post_booster_bar.setMinimum(1) self.post_booster_bar.setMaximum(10) self.pre_booster_switch.stateChanged.connect(self.toggle_pre_booster) self.pre_booster_bar.valueChanged.connect(self.control_pre_booster) self.distortion_switch.stateChanged.connect(self.toggle_distortion) self.distortion_bar.valueChanged.connect(self.control_distortion) self.phaser_switch.stateChanged.connect(self.toggle_phaser) self.post_booster_switch.stateChanged.connect(self.toggle_post_booster) self.post_booster_bar.valueChanged.connect(self.control_post_booster) """ Effect Switch Box """ self.switchBox = QtGui.QGridLayout() self.switchBox.addWidget(self.pre_booster_switch, 0, 0) self.switchBox.addWidget(self.pre_booster_bar, 1, 0) self.switchBox.addWidget(self.distortion_switch, 2, 0) self.switchBox.addWidget(self.distortion_bar, 3, 0) self.switchBox.addWidget(self.phaser_switch, 4, 0) self.switchBox.addWidget(self.post_booster_switch, 5, 0) self.switchBox.addWidget(self.post_booster_bar, 6, 0) """ Graph Widget """ self.graph = pg.PlotWidget(title="WaveForm") self.graphplt = self.graph.plotItem self.graphplt.setXRange(0, self.model.ANALYZEDSIZE) self.graphplt.setYRange(-1, 1) self.graphcurve = self.graphplt.plot() """ Spectrum Widget """ self.spectrum = pg.PlotWidget(title="Spectrum") self.specplt = self.spectrum.plotItem self.specplt.setXRange(0, 5000) self.specplt.setYRange(0, 10**12) # self.specplt.setYRange(0,20) self.speccurve = self.specplt.plot() """ Cepstrum Widget """ self.cepstrum = pg.PlotWidget(title="Cepstrum") self.cepsplt = self.cepstrum.plotItem self.cepsplt.setXRange(1019, 1029) self.cepsplt.setYRange(-3, 3) self.cepscurve = self.cepsplt.plot() """ Graph Box """ self.graphBox = QtGui.QGridLayout() self.graphBox.addWidget(self.graph, 0, 0) self.graphBox.addWidget(self.spectrum, 1, 0) self.graphBox.addWidget(self.cepstrum, 2, 0) """ Layout Box """ self.layoutBox = QtGui.QGridLayout() self.layoutBox.addLayout(self.switchBox, 0, 0) self.layoutBox.addLayout(self.graphBox, 0, 1) self.setLayout(self.layoutBox) """ timer """ self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(self.update_msec)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Image Widget addNapariGrayclipColormap() self.napariViewer = napari.Viewer(show=False) self.imgLayer = self.napariViewer.add_image(np.zeros((1, 1)), rgb=False, name='Reconstruction', colormap='grayclip') # Slider and edit box for choosing slice sliceLabel = QtWidgets.QLabel('Slice # ') self.sliceNum = QtWidgets.QLabel('0') self.sliceSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.sliceSlider.setMinimum(0) self.sliceSlider.setMaximum(0) self.sliceSlider.setTickInterval(5) self.sliceSlider.setSingleStep(1) self.sliceSlider.valueChanged[int].connect(self.sliceSliderMoved) baseLabel = QtWidgets.QLabel('Base # ') self.baseNum = QtWidgets.QLabel('0') self.baseSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.baseSlider.setMinimum(0) self.baseSlider.setMaximum(0) self.baseSlider.setTickInterval(5) self.baseSlider.setSingleStep(1) self.baseSlider.valueChanged[int].connect(self.baseSliderMoved) timeLabel = QtWidgets.QLabel('Time point # ') self.timeNum = QtWidgets.QLabel('0') self.timeSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.timeSlider.setMinimum(0) self.timeSlider.setMaximum(0) self.timeSlider.setTickInterval(5) self.timeSlider.setSingleStep(1) self.timeSlider.valueChanged[int].connect(self.timeSliderMoved) datasetLabel = QtWidgets.QLabel('Dataset # ') self.datasetNum = QtWidgets.QLabel('0') self.datasetSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.datasetSlider.setMinimum(0) self.datasetSlider.setMaximum(0) self.datasetSlider.setTickInterval(5) self.datasetSlider.setSingleStep(1) self.datasetSlider.valueChanged[int].connect(self.datasetSliderMoved) # Button group for choosing view self.chooseViewGroup = QtWidgets.QButtonGroup() self.chooseViewBox = QtWidgets.QGroupBox('Choose view') self.viewLayout = QtWidgets.QVBoxLayout() self.standardView = QtWidgets.QRadioButton('Standard view') self.standardView.viewName = 'standard' self.chooseViewGroup.addButton(self.standardView) self.viewLayout.addWidget(self.standardView) self.bottomView = QtWidgets.QRadioButton('Bottom side view') self.bottomView.viewName = 'bottom' self.chooseViewGroup.addButton(self.bottomView) self.viewLayout.addWidget(self.bottomView) self.leftView = QtWidgets.QRadioButton('Left side view') self.leftView.viewName = 'left' self.chooseViewGroup.addButton(self.leftView) self.viewLayout.addWidget(self.leftView) self.chooseViewBox.setLayout(self.viewLayout) self.chooseViewGroup.buttonClicked.connect(self.sigViewChanged) # List for storing sevral data sets self.reconList = QtWidgets.QListWidget() self.reconList.currentItemChanged.connect(self.sigItemSelected) self.reconList.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) removeReconBtn = BetterPushButton('Remove current') removeReconBtn.clicked.connect(self.removeRecon) removeAllReconBtn = BetterPushButton('Remove all') removeAllReconBtn.clicked.connect(self.removeAllRecon) # Set initial states self.standardView.setChecked(True) # Set layout layout = QtWidgets.QGridLayout() self.setLayout(layout) layout.addWidget(self.napariViewer.window._qt_window, 0, 0, 2, 1) layout.addWidget(self.chooseViewBox, 0, 1, 1, 2) layout.addWidget(self.reconList, 0, 3, 2, 1) layout.addWidget(self.sliceSlider, 2, 0) layout.addWidget(sliceLabel, 2, 1) layout.addWidget(self.sliceNum, 2, 2) layout.addWidget(self.baseSlider, 3, 0) layout.addWidget(baseLabel, 3, 1) layout.addWidget(self.baseNum, 3, 2) layout.addWidget(self.timeSlider, 4, 0) layout.addWidget(timeLabel, 4, 1) layout.addWidget(self.timeNum, 4, 2) layout.addWidget(self.datasetSlider, 5, 0) layout.addWidget(datasetLabel, 5, 1) layout.addWidget(self.datasetNum, 5, 2) layout.addWidget(removeReconBtn, 2, 3) layout.addWidget(removeAllReconBtn, 3, 3) layout.setRowStretch(1, 1) layout.setColumnStretch(0, 100) layout.setColumnStretch(2, 5)
V = np.ones_like(TAU) * v P_loss = kfric * W + kfric3 * W**3 + (res * (TAU / psi)**2) + k_v * (V - v_ref) P_mech = TAU * W P_loss[P_mech > 1.5e5] = np.NaN # green - orange - red Gradients['gor'] = { 'ticks': [(0.0, (74, 158, 71)), (0.5, (255, 230, 0)), (1, (191, 79, 76))], 'mode': 'rgb' } app = pg.mkQApp("NonUniform Image Example") win = QtWidgets.QMainWindow() cw = pg.GraphicsLayoutWidget() win.show() win.resize(600, 400) win.setCentralWidget(cw) win.setWindowTitle('pyqtgraph example: Non-uniform Image') p = cw.addPlot(title="Power Losses [W]", row=0, col=0) lut = pg.HistogramLUTItem(orientation="horizontal") p.setMouseEnabled(x=False, y=False) cw.nextRow() cw.addItem(lut)
""" import initExample ## Add path to library (just for examples; you do not need this) from pyqtgraph.Qt import QtGui, QtCore, QtWidgets, USE_PYSIDE import numpy as np import pyqtgraph as pg import pyqtgraph.ptime as ptime if USE_PYSIDE: import VideoTemplate_pyside as VideoTemplate else: import VideoTemplate_pyqt as VideoTemplate #QtGui.QApplication.setGraphicsSystem('raster') app = QtWidgets.QApplication([]) #mw = QtGui.QMainWindow() #mw.resize(800,800) win = QtWidgets.QMainWindow() win.setWindowTitle('pyqtgraph example: VideoSpeedTest') ui = VideoTemplate.Ui_MainWindow() ui.setupUi(win) win.show() ui.maxSpin1.setOpts(value=255, step=1) ui.minSpin1.setOpts(value=0, step=1) #ui.graphicsView.useOpenGL() ## buggy, but you can try it if you need extra speed. vb = pg.ViewBox() ui.graphicsView.setCentralItem(vb)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Focus lock self.kpEdit = QtWidgets.QLineEdit('5') self.kpLabel = QtWidgets.QLabel('kp') self.kiEdit = QtWidgets.QLineEdit('0.1') self.kiLabel = QtWidgets.QLabel('ki') self.lockButton = guitools.BetterPushButton('Lock') self.lockButton.setCheckable(True) self.lockButton.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) self.zStackBox = QtWidgets.QCheckBox('Z-stack') self.twoFociBox = QtWidgets.QCheckBox('Two foci') self.zStepFromEdit = QtWidgets.QLineEdit('40') self.zStepFromLabel = QtWidgets.QLabel('Min step (nm)') self.zStepToEdit = QtWidgets.QLineEdit('100') self.zStepToLabel = QtWidgets.QLabel('Max step (nm)') # self.focusDataBox = QtWidgets.QCheckBox('Save data') # Connect to exportData self.camDialogButton = guitools.BetterPushButton('Camera Dialog') # Piezo absolute positioning self.positionLabel = QtWidgets.QLabel( 'Position (µm)' ) # Potentially disregard this and only use in the positioning widget? self.positionEdit = QtWidgets.QLineEdit('50') self.positionSetButton = guitools.BetterPushButton('Set') # Focus lock calibration self.calibFromLabel = QtWidgets.QLabel('From (µm)') self.calibFromEdit = QtWidgets.QLineEdit('49') self.calibToLabel = QtWidgets.QLabel('To (µm)') self.calibToEdit = QtWidgets.QLineEdit('51') self.focusCalibButton = guitools.BetterPushButton('Calib') self.focusCalibButton.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) self.calibCurveButton = guitools.BetterPushButton('See calib') self.calibrationDisplay = QtWidgets.QLineEdit( 'Previous calib: none' ) # Edit this from the controller with calibration values self.calibrationDisplay.setReadOnly(True) # CREATE CALIBRATION CURVE WINDOW AND FOCUS CALIBRATION GRAPH SOMEHOW # Focus lock graph self.focusLockGraph = pg.GraphicsLayoutWidget() self.focusLockGraph.setAntialiasing(True) self.focusPlot = self.focusLockGraph.addPlot(row=1, col=0) self.focusPlot.setLabels(bottom=('Time', 's'), left=('Laser position', 'px')) self.focusPlot.showGrid(x=True, y=True) self.focusPlotCurve = self.focusPlot.plot( pen='y' ) # update this (self.focusPlotCurve.setData(X,Y)) with update(focusSignal) function # Webcam graph self.webcamGraph = pg.GraphicsLayoutWidget() self.camImg = pg.ImageItem(border='w') self.camImg.setImage(np.zeros((100, 100))) self.vb = self.webcamGraph.addViewBox(invertY=True, invertX=False) self.vb.setAspectLocked(True) self.vb.addItem(self.camImg) # PROCESS DATA THREAD - ADD SOMEWHERE ELSE, NOT HERE, AS IT HAS NO GRAPHICAL ELEMENTS! # GUI layout below grid = QtWidgets.QGridLayout() self.setLayout(grid) grid.addWidget(self.focusLockGraph, 0, 0, 1, 9) grid.addWidget(self.webcamGraph, 0, 9, 4, 1) grid.addWidget(self.focusCalibButton, 1, 2, 2, 1) grid.addWidget(self.calibrationDisplay, 3, 0, 1, 2) grid.addWidget(self.kpLabel, 1, 3) grid.addWidget(self.kpEdit, 1, 4) grid.addWidget(self.kiLabel, 2, 3) grid.addWidget(self.kiEdit, 2, 4) grid.addWidget(self.lockButton, 1, 5, 2, 1) grid.addWidget(self.zStackBox, 4, 2) grid.addWidget(self.twoFociBox, 4, 6) grid.addWidget(self.zStepFromLabel, 3, 4) grid.addWidget(self.zStepFromEdit, 4, 4) grid.addWidget(self.zStepToLabel, 3, 5) grid.addWidget(self.zStepToEdit, 4, 5) # grid.addWidget(self.focusDataBox, 4, 0, 1, 2) grid.addWidget(self.calibFromLabel, 1, 0) grid.addWidget(self.calibFromEdit, 1, 1) grid.addWidget(self.calibToLabel, 2, 0) grid.addWidget(self.calibToEdit, 2, 1) grid.addWidget(self.calibCurveButton, 3, 2) grid.addWidget(self.positionLabel, 1, 6) grid.addWidget(self.positionEdit, 1, 7) grid.addWidget(self.positionSetButton, 2, 6, 1, 2) grid.addWidget(self.camDialogButton, 3, 6, 1, 2)
async def process_profile_data(self): self.profile.connect(self.profile_addr) while True: await self.profile.recv_string() name = await self.profile.recv_string() data_type = await self.profile.recv_string() data = await self.profile.recv_serialized(self.deserializer, copy=False) if data_type == "profile": heartbeat = data['heartbeat'] version = data['version'] if heartbeat not in self.heartbeat_data: if version not in self.metadata: continue metadata = self.metadata[version] self.heartbeat_data[heartbeat] = HeartbeatData( data['heartbeat'], metadata) heartbeat_data = self.heartbeat_data[heartbeat] if name.startswith('worker'): heartbeat_data.add_worker_data(name, data['times']) elif name.startswith('localCollector'): heartbeat_data.add_local_collector_data( name, data['times']) elif name.startswith('globalCollector'): heartbeat_data.add_global_collector_data(data['times']) if version > self.current_version: self.current_version = version self.percent_per_heartbeat_data = collections.defaultdict( lambda: 0) if self.percent_per_heartbeat_trace: self.percent_per_heartbeat.removeItem( self.percent_per_heartbeat_trace) self.percent_per_heartbeat_trace = None parents = set() for k, v in self.metadata[version].items(): parent = v['parent'] parents.add(parent) if parent not in self.enabled_nodes: widget = QtWidgets.QCheckBox(self.widget) widget.node = parent widget.setCheckState(QtCore.Qt.Checked) self.enabled_nodes[parent] = widget self.trace_layout.addRow(parent, widget) deleted_nodes = self.parents.difference(parents) for node in deleted_nodes: self.trace_layout.removeRow( self.enabled_nodes[node]) del self.enabled_nodes[node] trace = self.time_per_heartbeat_traces[node] self.time_per_heartbeat.removeItem(trace) self.time_per_heartbeat_legend.removeItem(trace) del self.time_per_heartbeat_traces[node] del self.time_per_heartbeat_data[node] self.parents = parents self.trace_group.sigChanged.disconnect( self.state_changed) self.trace_group = WidgetGroup() self.trace_group.sigChanged.connect(self.state_changed) for node, ctrl in self.enabled_nodes.items(): self.trace_group.addWidget(ctrl, node) self.time_per_heartbeat_data["heartbeat"][-1] = heartbeat self.time_per_heartbeat_data["heartbeat"] = np.roll( self.time_per_heartbeat_data["heartbeat"], -1) total = 1 for node, time in heartbeat_data.total_time_per_heartbeat.items( ): self.time_per_heartbeat_data[node][-1] = time self.time_per_heartbeat_data[node] = np.roll( self.time_per_heartbeat_data[node], -1) self.percent_per_heartbeat_data[ node] = time / heartbeat_data.total_heartbeat_time total -= time / heartbeat_data.total_heartbeat_time self.percent_per_heartbeat_data['Transfer'] = total i = 0 for node, times in self.time_per_heartbeat_data.items(): if node == "heartbeat": continue if node not in self.time_per_heartbeat_traces: symbol, color = symbols_colors[i] self.time_per_heartbeat_traces[ node] = self.time_per_heartbeat.plot( x=self. time_per_heartbeat_data["heartbeat"], y=times, name=node, symbol=symbol, symbolBrush=color) else: self.time_per_heartbeat_traces[node].setData( x=self.time_per_heartbeat_data["heartbeat"], y=times) i += 1 nodes, times = zip( *self.percent_per_heartbeat_data.items()) if self.percent_per_heartbeat_trace is None: x = np.arange(len(nodes)) self.percent_per_heartbeat_trace = pg.BarGraphItem( x=x, height=times, width=1, brush='b') self.percent_per_heartbeat.addItem( self.percent_per_heartbeat_trace) xticks = dict(zip(x, nodes)) ax = self.percent_per_heartbeat.getAxis('bottom') ax.setTicks([xticks.items()]) else: self.percent_per_heartbeat_trace.setOpts(height=times) self.heartbeats_per_second_data[ -1] = 1 / heartbeat_data.total_heartbeat_time self.heartbeats_per_second_data = np.roll( self.heartbeats_per_second_data, -1) if self.heartbeats_per_second_trace is None: symbol, color = symbols_colors[0] self.heartbeats_per_second_trace = self.heartbeats_per_second.plot( x=self.time_per_heartbeat_data["heartbeat"], y=self.heartbeats_per_second_data, symbol=symbol, symbolBrush=color) else: self.heartbeats_per_second_trace.setData( x=self.time_per_heartbeat_data["heartbeat"], y=self.heartbeats_per_second_data) now = dt.datetime.now() now = now.strftime("%H:%M:%S") last_updated = f"Last Updated: {now}" self.last_updated.setText(last_updated) text = f"Seconds/Heartbeat: {heartbeat_data.total_heartbeat_time:.6f}<br/>Heartbeat: {heartbeat}" self.total_heartbeat_time.setText(text) text = f"Heartbeats/Second: {1/heartbeat_data.total_heartbeat_time:.0f}<br/>Heartbeat: {heartbeat}" self.heartbeat_per_second.setText(text) del self.heartbeat_data[heartbeat] elif data_type == "metadata": graph_name = data['graph'] version = data['version'] logger.info("Received metadata for %s v%d", graph_name, version) self.metadata[version] = data['metadata']
def __init__(self): super(Window, self).__init__() self.setWindowTitle('Smart Car Project') self.setWindowIcon(QtGui.QIcon('logo.png')) plot = Graph() exit_button = QtWidgets.QPushButton("Exit", self) exit_button.clicked.connect(self.close_application) yellow_t_input = QtWidgets.QLineEdit(self) yellow_t_input.setPlaceholderText( 'Duration of yellow traffic light, Ty (2s – 4s)') yellow_t_input.setValidator(QtGui.QDoubleValidator(2.00, 4.00, 2)) yellow_t_input.textChanged.connect(lambda: plot.clear()) yellow_t_input.textChanged.connect( lambda: plot.set_t_yellow(yellow_t_input.text())) yellow_t_input.textChanged.connect(plot.plot_real_time) yellow_t_input.textChanged.connect(plot.show) a_max_input = QtWidgets.QLineEdit(self) a_max_input.setPlaceholderText( 'Maximum acceleration of the car (m/s^2)') a_max_input.setValidator(QtGui.QDoubleValidator(0.00, 3.00, 2)) a_max_input.textChanged.connect(lambda: plot.clear()) a_max_input.textChanged.connect( lambda: plot.set_a_max(a_max_input.text())) a_max_input.textChanged.connect(plot.plot_real_time) a_max_input.textChanged.connect(plot.show) a_min_input = QtWidgets.QLineEdit(self) a_min_input.setPlaceholderText( 'Minimum acceleration of the car (m/s^2)') a_min_input.setValidator(QtGui.QDoubleValidator(-3.00, 0.00, 2)) a_min_input.textChanged.connect(lambda: plot.clear()) a_min_input.textChanged.connect( lambda: plot.set_a_min(a_min_input.text())) a_min_input.textChanged.connect(plot.plot_real_time) a_min_input.textChanged.connect(plot.show) v_current_input = QtWidgets.QLineEdit(self) v_current_input.setPlaceholderText( 'Vehicle’s current speed, V0 (20 km/h – 80 km/h)') v_current_input.setValidator(QtGui.QDoubleValidator(20.00, 80.00, 2)) v_current_input.textChanged.connect(lambda: plot.clear()) v_current_input.textChanged.connect( lambda: plot.set_v_current(v_current_input.text())) v_current_input.textChanged.connect(plot.plot_real_time) v_current_input.textChanged.connect(plot.show) distance_input = QtWidgets.QLineEdit(self) distance_input.setPlaceholderText( 'Distance to the intersection, D (7m – 50m)') distance_input.setValidator(QtGui.QDoubleValidator(7.00, 50.00, 2)) distance_input.textChanged.connect(lambda: plot.clear()) distance_input.textChanged.connect( lambda: plot.set_distance(distance_input.text())) distance_input.textChanged.connect(plot.plot_real_time) distance_input.textChanged.connect(plot.show) length_input = QtWidgets.QLineEdit(self) length_input.setPlaceholderText( 'Length of the intersection, L (7m – 20m)') length_input.setValidator(QtGui.QDoubleValidator(7.00, 20.00, 2)) length_input.textChanged.connect(lambda: plot.clear()) length_input.textChanged.connect( lambda: plot.set_length(length_input.text())) length_input.textChanged.connect(plot.plot_real_time) length_input.textChanged.connect(plot.show) v_max_input = QtWidgets.QLineEdit(self) v_max_input.setPlaceholderText('Speed Limit (km/h)') v_max_input.setValidator(QtGui.QDoubleValidator(40.00, 90.00, 2)) v_max_input.textChanged.connect(lambda: plot.clear()) v_max_input.textChanged.connect( lambda: plot.set_v_max(v_max_input.text())) v_max_input.textChanged.connect(plot.plot_real_time) v_max_input.textChanged.connect(plot.show) position_indicator = QtWidgets.QLabel() position_indicator.setText( "<span style='font-size: 13pt, '> Coordinates: a = 0 (m/s^2), <span style='', 'font-size: 13pt'> d = 0 (m)</span>" ) plot.set_coordinates_indicate(position_indicator) descriptlabel = QtWidgets.QLabel( '\nPlease input the variables to plot our graph' '\n\nMouse should be used to navigate the graph' '\n\nRight click on the graph to show the options' '\n\n\nNote: do not completely remove the entered variables to escape' '\nthe crashing of the app (the program is in the beta version)') authorlabel = QtWidgets.QLabel( '\n\nMark Hovsepyan\nAmerican University of Armenia\nClass: Mechanics\nInstructor: Arsen Tonoyan\nProject Title: Smart Car Project' ) layout = QtWidgets.QGridLayout(self) layout.addWidget(distance_input, 1, 3) layout.addWidget(length_input, 2, 3) layout.addWidget(a_max_input, 3, 3) layout.addWidget(a_min_input, 4, 3) layout.addWidget(yellow_t_input, 5, 3) layout.addWidget(v_current_input, 6, 3) layout.addWidget(v_max_input, 7, 3) layout.addWidget(exit_button, 11, 2, 1, 2) layout.addWidget(position_indicator, 11, 1) layout.addWidget(plot, 1, 1, 10, 1) layout.addWidget(descriptlabel, 8, 2, 1, 2) layout.addWidget(authorlabel, 10, 2, 1, 2) authorlabel.setAlignment(QtCore.Qt.AlignRight) descriptlabel.setAlignment(QtCore.Qt.AlignCenter) self.resize(1000, 600) self.show()
# -*- coding: utf-8 -*- """ This example demonstrates the different auto-ranging capabilities of ViewBoxes """ import initExample ## Add path to library (just for examples; you do not need this) from pyqtgraph.Qt import QtGui, QtCore, QtWidgets import numpy as np import pyqtgraph as pg #QtGui.QApplication.setGraphicsSystem('raster') app = QtWidgets.QApplication([]) #mw = QtGui.QMainWindow() #mw.resize(800,800) win = pg.GraphicsWindow(title="Plot auto-range examples") win.resize(800,600) win.setWindowTitle('pyqtgraph example: PlotAutoRange') d = np.random.normal(size=100) d[50:54] += 10 p1 = win.addPlot(title="95th percentile range", y=d) p1.enableAutoRange('y', 0.95) p2 = win.addPlot(title="Auto Pan Only") p2.setAutoPan(y=True) curve = p2.plot()
def test_basics_graphics_view(): view = pg.GraphicsView() background_role = view.backgroundRole() assert background_role == QtGui.QPalette.ColorRole.Window assert view.backgroundBrush().color() == QtGui.QColor(0, 0, 0, 255) assert view.focusPolicy() == QtCore.Qt.FocusPolicy.StrongFocus assert view.transformationAnchor() == QtWidgets.QGraphicsView.ViewportAnchor.NoAnchor minimal_update = QtWidgets.QGraphicsView.ViewportUpdateMode.MinimalViewportUpdate assert view.viewportUpdateMode() == minimal_update assert view.frameShape() == QtWidgets.QFrame.Shape.NoFrame assert view.hasMouseTracking() is True # Default properties # -------------------------------------- assert view.mouseEnabled is False assert view.aspectLocked is False assert view.autoPixelRange is True assert view.scaleCenter is False assert view.clickAccepted is False assert view.centralWidget is not None assert view._background == "default" # Set background color # -------------------------------------- view.setBackground("w") assert view._background == "w" assert view.backgroundBrush().color() == QtCore.Qt.GlobalColor.white # Set anti aliasing # -------------------------------------- aliasing = QtGui.QPainter.RenderHint.Antialiasing # Default is set to `False` assert view.renderHints() & aliasing != aliasing view.setAntialiasing(True) assert view.renderHints() & aliasing == aliasing view.setAntialiasing(False) assert view.renderHints() & aliasing != aliasing # Enable mouse # -------------------------------------- view.enableMouse(True) assert view.mouseEnabled is True assert view.autoPixelRange is False view.enableMouse(False) assert view.mouseEnabled is False assert view.autoPixelRange is True # Add and remove item # -------------------------------------- central_item = QtWidgets.QGraphicsWidget() view.setCentralItem(central_item) assert view.centralWidget is central_item # XXX: Removal of central item is not clear in code scene = view.sceneObj assert isinstance(scene, pg.GraphicsScene) assert central_item in scene.items() item = QtWidgets.QGraphicsWidget() assert item not in scene.items() view.addItem(item) assert item in scene.items() view.removeItem(item) assert item not in scene.items() # Close the graphics view # -------------------------------------- view.close() assert view.centralWidget is None assert view.currentItem is None assert view.sceneObj is None assert view.closed is True