def __init__(self): QWidget.__init__(self) # Set filename to read designer_file = QFile("ui.ui") # Open UI file designer_file.open(QFile.ReadOnly) # Call file loader loader = QUiLoader() # Pass MplWidget to loader so it knows what to do when it reads it from UI file loader.registerCustomWidget(MplWidget) # Load file self.ui = loader.load(designer_file, self) # Don't need the file anymore, close it. designer_file.close() # Assign radial button ids self.ui.sensor.setId(self.ui.rad_0, 0) self.ui.sensor.setId(self.ui.rad_1, 1) self.ui.sensor.setId(self.ui.rad_2, 2) self.ui.sensor.setId(self.ui.rad_3, 3) # Assigns action to button self.ui.sensor.buttonClicked.connect(self.get_sensor) self.ui.btn_serial_refresh.clicked.connect(self.get_serial_ports) self.ui.btn_serial_connect.clicked.connect(self.connect_to_serial) self.ui.s_f.valueChanged.connect(self.fft_at_f) self.ui.btn_mp.clicked.connect(self.calc_mp) self.ui.btn_vt.clicked.connect(self.calc_vt_mc_a0) self.ui.btn_ma.clicked.connect(self.calc_ma_mb) self.ui.btn_limpiar.clicked.connect(self.clear_v_fields) self.ui.btn_v0.clicked.connect(lambda: self.copy_val_at_f(self.ui.le_v0)) self.ui.btn_v1.clicked.connect(lambda: self.copy_val_at_f(self.ui.le_v1)) self.ui.btn_v2.clicked.connect(lambda: self.copy_val_at_f(self.ui.le_v2)) self.ui.btn_v3.clicked.connect(lambda: self.copy_val_at_f(self.ui.le_v3)) # self.ui.btn_rndSignal.clicked.connect(self.update_graph) # Button removed # This function is called in a thread created on the first time you call connect_to_serial # Set process self.freq = 16 self.stop_event = threading.Event() self.reading = threading.Event() self.sensor = 0 self.method = threading.Thread(target=self.update_graph, name='Data update', args=(), daemon=True) self.serial = serial.Serial(port=None, baudrate=115200, timeout=1.5) # Changes the UI title. Cannot be done from designer as we are adding a widget,not defining mainwindow. self.setWindowTitle("Método de las cuatro corridas sin fase") # self.setWindowIcon(QIcon('icon.png')) self.setWindowIcon(QPixmap.fromImage('icon.png')) # Create a grid layout # grid_layout = QGridLayout() # Adds what was loaded from file to layout # grid_layout.addWidget(self.ui) # Sets window layout to created grid layout # self.setLayout(grid_layout) self.setLayout(self.ui.layout())
def registerCustomWidget(self, class_): """ Register a class with the UiLoader that has been used with Qt Designers "promote to" functionality. """ self._custom_widgets[class_.__name__] = class_ QUiLoader.registerCustomWidget(self, class_)
def __init__(self): QWidget.__init__(self) #Read UI file designer_file = QFile("UI.ui") designer_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui = loader.load(designer_file, self) designer_file.close() #end of reading from UI file #plot btn listener self.ui.plotbtn.clicked.connect(self.update_graph) #exit btn listener self.ui.exitbtn.clicked.connect(self.exitapp) #set title self.setWindowTitle("Plotter") #set window icon "plotter.png" self.setIcon() #intializing grilayout and setting it grid_layout = QGridLayout() grid_layout.addWidget(self.ui) self.setLayout(grid_layout) self.valid = True
def __init__(self): QWidget.__init__(self) designer_file = QFile("iothook.ui") designer_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui = loader.load(designer_file, self) designer_file.close() self.setWindowTitle("IOTHOOK") self.field_1_list = [] self.field_2_list = [] self.field_3_list = [] self.field_4_list = [] self.field_5_list = [] self.field_6_list = [] self.field_7_list = [] self.field_8_list = [] self.lineEdit = self.ui.findChild(QLineEdit, 'lineEdit') self.pushButton = self.ui.findChild(QPushButton, 'pushButton') self.pushButton.clicked.connect(self.result) grid_layout = QGridLayout() grid_layout.addWidget(self.ui) self.setLayout(grid_layout)
def load_from_file(filepath): ui_file = QFile(filepath) ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(MainWindow) window = loader.load(ui_file) ui_file.close() return window
def load_ui(app, fn): loader = QUiLoader(parent=app) uifile = QFile(fn) uifile.open(QFile.ReadOnly) loader.registerCustomWidget(ImageView) ui = loader.load(uifile, None) uifile.close() return ui
def testPythonCustomWidgets(self): w = QtWidgets.QWidget() loader = QUiLoader() loader.registerCustomWidget(MyWidget) filePath = os.path.join(os.path.dirname(__file__), 'pycustomwidget.ui') result = loader.load(filePath, w) self.assertTrue(isinstance(result.custom, MyWidget)) self.assertTrue(result.custom.isPython())
def load_ui(self): loader = QUiLoader() loader.registerCustomWidget(drawing_grid.DrawingGrid) path = os.path.join(os.path.dirname(__file__), "form.ui") ui_file = QFile(path) ui_file.open(QFile.ReadOnly) self.ui = loader.load(ui_file, self) self.ui.drawing_grid.grid_content = self.main_controller.game_of_life.board ui_file.close()
def testPythonCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() loader.registerCustomWidget(MyWidget) filePath = os.path.join(os.path.dirname(__file__), "pycustomwidget.ui") result = loader.load(filePath, w) self.assert_(isinstance(result.custom, MyWidget)) self.assert_(result.custom.isPython())
def create_dialog(parent=None): ui_file = QFile('settings.ui') ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(SettingsDialog) win = loader.load(ui_file, parent) ui_file.close() return win
def __init__(self): self.Manip = Manipulation() loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui = loader.load('UIs/main.ui') self.ui.MplWidget.canvas.axes = self.ui.MplWidget.canvas.figure.add_axes( [0.16, 0.15, 0.77, 0.77]) self.set_ui_connect() self.ui.show()
def __init__(self, parent=None): super(InfoDialog, self).__init__(parent) ui_file_name = "ui/Ui_Dialog.ui" ui_file = QFile(ui_file_name) loader = QUiLoader() loader.registerCustomWidget(Dialog) self.ui = loader.load(ui_file) print(self.ui.__class__) ui_file.close()
def loadUiWidget(uifilename, parent=None, customWidgets=[]): uifilename = os.path.join(file_dir, uifilename) loader = QUiLoader() for widget in customWidgets: loader.registerCustomWidget(widget) uifile = QFile(uifilename) uifile.open(QFile.ReadOnly) ui = loader.load(uifile, parent) uifile.close() return ui
def __init__(self): self.Nor = Normalization() self.sample_names = [] self.all_data = pd.DataFrame() loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui_comparation = loader.load('UIs/comparation.ui') self.ui_comparation.widget.canvas.axes = self.ui_comparation.widget.canvas.figure.add_axes( [0.12, 0.12, 0.8, 0.8]) self.set_ui_comparation_connect() self.ui_comparation.show()
def start(self, *a, **kw): path = os.path.dirname(os.path.realpath(__file__)) + "\\" file = QFile(path + "gui.ui") file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(QMainWindow_S) self.window = loader.load(file) # Global key press eventFilter.signal emits self.keyEvent = self.KeyEventFilter() self.parent.installEventFilter(self.keyEvent) # self.keyEvent.signal.connect(...) self.stacked_widget = QStackedWidget() # layout = QVBoxLayout() # layout.addWidget(self.window.centralwidget) self.window.setCentralWidget(self.stacked_widget) self.window.show()
def __init__(self): # 从文件中加载UI定义 loader = QUiLoader() loader.registerCustomWidget(pg.PlotWidget) self.ui = QUiLoader().load('main.ui') self.ui.Simulation.clicked.connect(self.simulator) self.ui.Make_map.clicked.connect(self.makemap) self.ui.Robot_num.setValue(50) self.ui.Map_filename_read.setText('map1.txt') self.ui.Alpha.setValue(0.1) self.ui.Len.setValue(10) self.ui.Total_time.setValue(1) self.ui.Cover_ratio.setValue(0.99) self.ui.Map_xlen.setValue(100) self.ui.Map_ylen.setValue(100) self.ui.progressBar.setRange(0, 100) self.ui.progressBar.setValue(0) self.ui.Coverage_time.setBackground('w') self.ui.Coverage_time.setYRange(min=0, max=1000) self.curve = self.ui.Coverage_time.getPlotItem().plot( pen=pg.mkPen('r', width=1))
def __init__(self, title, x_list, y_list): QWidget.__init__(self) base_dir = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(base_dir, 'ui') self.path = path self.ui_path = self.path + '/graph.ui' designer_file = QFile(self.ui_path) designer_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui = loader.load(designer_file, self) designer_file.close() grid_layout = QGridLayout() grid_layout.addWidget(self.ui) self.setLayout(grid_layout) self.ui.MplWidget.canvas.axes.clear() self.ui.MplWidget.canvas.axes.plot(x_list, y_list) self.ui.MplWidget.canvas.axes.set_title(title) self.ui.MplWidget.canvas.draw()
Author: Kwon-Young Choi Email: [email protected] Date: 2019-08-12 Description: main """ import sys from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication from PySide2 import QtCore from PySide2.QtCore import QFile, QCoreApplication from pyqt_corrector.mainwindow import MainWindow from pyqt_corrector.smoothview import SmoothView from pyqt_corrector.tabwidget import TabWidget if __name__ == "__main__": QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) app = QApplication([]) file = QFile("data/mainwindow.ui") file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(MainWindow) loader.registerCustomWidget(SmoothView) loader.registerCustomWidget(TabWidget) main_window = loader.load(file) main_window.setupUi() main_window.show() sys.exit(app.exec_())
def __init__(self, ui_file, parent=None): super(Form, self).__init__(parent) ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(InterfaceWindow) self.window = loader.load(ui_file) ui_file.close() self.window.set_reload_ref(self.reload_viewer) # system flags self.current_data_dir = "." # new task window self.in_task = False # indicating its currently performing a Task self.newTaskWin = NewTask(ui_file='newtaskwindow.ui') # Menu actions ================================================== # Load ADS action self.window.findChild(QAction, 'loadAOAction').\ triggered.connect(self.load_adc) # Load from video self.window.findChild(QAction, 'actionFrom_Video').\ triggered.connect(self.get_active_from_video) self.window.findChild(QAction, 'actionFrom_Video').\ setEnabled(False) # load save target mod action self.window.findChild(QAction, 'actionTarget_Modifications').\ triggered.connect(self.save_mods) # show change history self.window.findChild(QAction, 'actionView_history').\ triggered.connect(self.show_mods) # save active data to .. self.window.findChild(QAction, 'actionActive_data_to').\ triggered.connect(self.save_active_to) # Tools ----------- # data spliter self.window.findChild(QAction, 'actionData_spliter').\ triggered.connect(self.run_spliter) # renamer self.window.findChild(QAction, 'actionRename').\ triggered.connect(self.run_rename) # check labels self.window.findChild(QAction, 'actionCheck_Labels').\ triggered.connect(self.check_labels_integrity) # set defult class self.window.findChild(QAction, 'actionset_defult_class').\ triggered.connect(self.set_defult_class) # For task ------------------------------------------------------ self.window.findChild(QAction, 'actionNewTask').\ triggered.connect(self.new_task) self.window.findChild(QAction, 'actionOpenTask').\ triggered.connect(self.open_task) # Data list ===================================================== self.dataList = \ self.window.findChild(QListWidget, 'dataList') self.dataList.setViewMode(QListView.IconMode) self.dataList.setIconSize(PySide2.QtCore.QSize(128, 72)) self.dataList.itemSelectionChanged.connect(self.load_viewer) self.dataList.itemDoubleClicked.connect(self.double_click_data) # Data Viewer =================================================== self.viewerScene = ImgScene(self) self.viewerView = self.window.findChild(QGraphicsView, 'dataViewer') self.viewerView.setScene(self.viewerScene) self.viewerView.setCursor(QCursor(PySide2.QtCore.Qt.CrossCursor)) # Targets list ================================================== self.targetList = \ self.window.findChild(QListWidget, 'targetList') self.targetList.itemClicked.connect(self.hightlight_target) # self.current_dataScene = DataScene(self.viewerScene, \ # self.viewerView, self.targetList) # self.targetList.itemDoubleClicked.connect(\ # self.current_dataScene.edit_target_class) # editing buttons =============================================== self.rmTargetButton = \ self.window.findChild(QPushButton, 'rmTargetButton') self.undoButton = \ self.window.findChild(QPushButton, 'undoButton') self.editButton = \ self.window.findChild(QPushButton, 'editButton') self.deleteButton = \ self.window.findChild(QPushButton, 'deleteButton') self.editButton_connected = False # make sure only connect once self.rmTargetButton.setEnabled(False) self.undoButton.setEnabled(False) self.rmTargetButton.clicked.connect(\ lambda state=0, x=-1:\ self.remove_target(x)) self.targetList_modified = False self.undoButton.clicked.connect(self.undo_mod) self.deleteButton.clicked.connect(self.remove_img) # shortcuts ==================================================== QShortcut(QKeySequence("Ctrl+R"), self.window).activated.\ connect(lambda state=0, x=-1: self.remove_target(x)) self.window.show()
def __init__(self, config, dir_, machine_list): QWidget.__init__(self) # init and load ui self.dir_ = dir_ self.config = config self.machine_list = machine_list self.ind = 0 self.tag_quantile = 0 self.data = None self.lr = -1 self.lr_list = [] self.x_list = [] self.segments = 0 self.anomaly_length = 0 self.lines = [] self.data_button = None self.merge = False ui_file = QFile('label_page.ui') ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(PlotWidget) self.ui = loader.load(ui_file, self) self.setFixedSize(1450, 900) self.ui.machine_label.setPixmap(QPixmap('images/machine1.png')) ui_file.close() self.setWindowTitle('Label Tool') # add button to choose machine machine_layout = QVBoxLayout() machine_layout.setSpacing(10) button_list = [QPushButton(machine) for machine in machine_list] for i, button in enumerate(button_list): button.setFixedSize(205, 40) if i == 0: button.setIcon(QIcon(QPixmap('images/line_blue.png'))) button.setStyleSheet( "QPushButton{background-color:rgb(2,34,63);font-family:'Calibri';font-size:20px;color:rgb(24,144,255);}" ) self.data_button = button else: button.setIcon(QIcon(QPixmap('images/line.png'))) button.setStyleSheet( "QPushButton{font-family:'Calibri';font-size:20px;color:white;}" ) button.clicked.connect(self.jump) machine_layout.addWidget(button) machine_layout.addStretch() self.ui.scrollAreaWidgetContents.setLayout(machine_layout) # load the data of first machine machine = self.machine_list[self.ind] data = self._read_data(machine) self.data = data self.merge_kpi, self.merge_str = self.kpi_2be_merged(self.data) # init figure and draw kpi time series of first machine self.init_figure(data, self.merge) self.canvas = self.ui.plot_widget.canvas CustomedToolbar(self.canvas, self.ui.toolBar_widget) self.draw(data, self.merge) self.canvas.mpl_connect('scroll_event', self._zoom) self.canvas.mpl_connect('button_press_event', self._zoom) self.canvas.mpl_connect('button_press_event', self._label) # set function button and add some information bars self.ui.timeInterval_button.setText(self.config['time_interval']) self.ui.mergeKPIs_button.setText(self.merge_str + 'To\n' + str(self.merge_kpi[-1])) if self.config['date']: start = time.localtime(data['timestamp'][0]) start = time.strftime("%Y/%m/%d\n%H:%M:%S", start) end = time.localtime(data['timestamp'][len(data['timestamp']) - 1]) end = time.strftime("%Y/%m/%d\n%H:%M:%S", end) else: start = '0' end = str(data['value'].shape[0] - 1) info = 'Start Index: ' + start + ' — End Index: ' + end self.ui.info_label.setText('| ' + info) self.ui.startIndex_button.setText(start) self.ui.endIndex_button.setText(end) self.ui.finish_button.clicked.connect(self.finish) self.ui.merge_button.clicked.connect(self.merge_seperate) self.setWindowIcon(QIcon('images/logo.png'))
def __init__(self): QObject.__init__(self) self.module_path = os.path.dirname(__file__) self.mouse_pressed = False self.draw_ellipse = False self.write_text = False self.mouse_pressed_x = 0 self.mouse_pressed_y = 0 self.tables = [] self.ellipses = [] self.texts = [] self.text_event_filter = TextEventFilter(self) # loading widgets from designer file loader = QUiLoader() loader.registerCustomWidget(QtCharts.QChartView) self.window = loader.load(self.module_path + "/ui/application_window.ui") self.tab_widget = self.window.findChild(QTabWidget, "tab_widget") chart_frame = self.window.findChild(QFrame, "chart_frame") chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame") self.chart_view = self.window.findChild(QtCharts.QChartView, "chart_view") button_add_tab = self.window.findChild(QPushButton, "button_add_tab") button_reset_zoom = self.window.findChild(QPushButton, "button_reset_zoom") button_save_image = self.window.findChild(QPushButton, "button_save_image") self.label_mouse_coords = self.window.findChild( QLabel, "label_mouse_coords") self.radio_zoom = self.window.findChild(QRadioButton, "radio_zoom") self.radio_ellipse = self.window.findChild(QRadioButton, "radio_ellipse") self.radio_text = self.window.findChild(QRadioButton, "radio_text") # Creating QChart self.chart = QtCharts.QChart() self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations) self.chart.setTheme(QtCharts.QChart.ChartThemeLight) self.chart.setAcceptHoverEvents(True) self.axis_x = QtCharts.QValueAxis() self.axis_x.setTitleText("PC1") self.axis_x.setRange(-10, 10) self.axis_x.setLabelFormat("%.1f") self.axis_y = QtCharts.QValueAxis() self.axis_y.setTitleText("PC2") self.axis_y.setRange(-10, 10) self.axis_y.setLabelFormat("%.1f") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.chart_view.setChart(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand) # 1 tab by default self.add_tab() # custom stylesheet style_file = QFile(self.module_path + "/ui/custom.css") style_file.open(QFile.ReadOnly) self.window.setStyleSheet(style_file.readAll().data().decode("utf-8")) style_file.close() # effects self.tab_widget.setGraphicsEffect(self.card_shadow()) chart_frame.setGraphicsEffect(self.card_shadow()) chart_cfg_frame.setGraphicsEffect(self.card_shadow()) button_add_tab.setGraphicsEffect(self.button_shadow()) button_reset_zoom.setGraphicsEffect(self.button_shadow()) button_save_image.setGraphicsEffect(self.button_shadow()) # signal connection self.tab_widget.tabCloseRequested.connect(self.remove_tab) button_add_tab.clicked.connect(self.add_tab) button_reset_zoom.clicked.connect(self.reset_zoom) button_save_image.clicked.connect(self.save_image) self.radio_zoom.toggled.connect(self.on_mouse_function_changed) self.radio_ellipse.toggled.connect(self.on_mouse_function_changed) self.radio_text.toggled.connect(self.on_mouse_function_changed) # event filter self.chart.installEventFilter(self) # show window self.window.show()
def __init__(self): self.env = None loader = QUiLoader() loader.registerCustomWidget(pg.PlotWidget) self.ui = loader.load(os.path.abspath('..') + "\\ui\\main.ui") self.cur_draw_age = 0 self.ui.plot_animals.addLegend() self.curve_amount_tiger = self.ui.plot_animals.getPlotItem().plot( pen=pg.mkPen('r', width=1), name='Tiger Amount') self.curve_amount_wolf = self.ui.plot_animals.getPlotItem().plot( pen=pg.mkPen('g', width=1), name='Wolf Amount') self.curve_amount_sheep = self.ui.plot_animals.getPlotItem().plot( pen=pg.mkPen('b', width=1), name='Sheep Amount') self.curve_amount_grass = self.ui.plot_animals.getPlotItem().plot( pen=pg.mkPen('y', width=1), name='Grass Amount') self.ui.plot_animals_change.addLegend() self.curve_add_tiger = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('r', width=1), name='Tiger Born') self.curve_sub_tiger = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('g', width=1), name='Tiger Dead') self.curve_add_wolf = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('b', width=1), name='Wolf Born') self.curve_sub_wolf = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('c', width=1), name='Wolf Dead') self.curve_add_sheep = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('m', width=1), name='Sheep Born') self.curve_sub_sheep = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('y', width=1), name='Sheep Dead') self.curve_sub_grass = self.ui.plot_animals_change.getPlotItem().plot( pen=pg.mkPen('d', width=1), name='Grass Cost') self.ui.plot_tiger_gene.addLegend() self.curve_tiger_gene_hungry_level = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('r', width=1), name='Hungry Level') self.curve_tiger_gene_lifespan = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('y', width=1), name='LifeSpan') self.curve_tiger_gene_fightCapability = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('g', width=1), name='fightCapability') self.curve_tiger_gene_age = self.ui.plot_tiger_gene.getPlotItem().plot( pen=pg.mkPen('w', width=1), name='Age') self.curve_tiger_gene_attack = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('c', width=1), name='AttackPossibility') self.curve_tiger_gene_defend = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('m', width=1), name='DefendPossibility') self.curve_tiger_gene_breed = self.ui.plot_tiger_gene.getPlotItem( ).plot(pen=pg.mkPen('b', width=1), name='BreedingTimes') self.ui.plot_wolf_gene.addLegend() self.curve_wolf_gene_hungry_level = self.ui.plot_wolf_gene.getPlotItem( ).plot(pen=pg.mkPen('r', width=1), name='Hungry Level') self.curve_wolf_gene_lifespan = self.ui.plot_wolf_gene.getPlotItem( ).plot(pen=pg.mkPen('y', width=1), name='LifeSpan') self.curve_wolf_gene_fightCapability = self.ui.plot_wolf_gene.getPlotItem( ).plot(pen=pg.mkPen('g', width=1), name='fightCapability') self.curve_wolf_gene_age = self.ui.plot_wolf_gene.getPlotItem().plot( pen=pg.mkPen('w', width=1), name='Age') self.curve_wolf_gene_attack = self.ui.plot_wolf_gene.getPlotItem( ).plot(pen=pg.mkPen('c', width=1), name='AttackPossibility') self.curve_wolf_gene_defend = self.ui.plot_wolf_gene.getPlotItem( ).plot(pen=pg.mkPen('m', width=1), name='DefendPossibility') self.curve_wolf_gene_breed = self.ui.plot_wolf_gene.getPlotItem().plot( pen=pg.mkPen('b', width=1), name='BreedingTimes') self.ui.plot_sheep_gene.addLegend() self.curve_sheep_gene_hungry_level = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('r', width=1), name='Hungry Level') self.curve_sheep_gene_lifespan = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('y', width=1), name='LifeSpan') self.curve_sheep_gene_fightCapability = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('g', width=1), name='fightCapability') self.curve_sheep_gene_age = self.ui.plot_sheep_gene.getPlotItem().plot( pen=pg.mkPen('w', width=1), name='Age') self.curve_sheep_gene_attack = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('c', width=1), name='AttackPossibility') self.curve_sheep_gene_defend = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('m', width=1), name='DefendPossibility') self.curve_sheep_gene_breed = self.ui.plot_sheep_gene.getPlotItem( ).plot(pen=pg.mkPen('b', width=1), name='BreedingTimes') self.ui.simulate_btn.clicked.connect(self.simulate_clicked) self.ui.pause_btn.clicked.connect(self.pause_clicked) #设置时间区间修改事件监听 self.age_range = int(self.ui.age_range_edit.text()) self.ui.age_range_edit.editingFinished.connect( self.age_range_edit_finished) #后台线程通知更新进化数据 # global_ms.draw.connect(self.update_env) #当前是否在处理模拟暂停或者模拟恢复,因为暂停或恢复需要等待小段时间,期间不要让再次点击 self.pause_click_handling = False self.pause_status = False #后台线程运行的逻辑 self.bg_running_obj = EvolutionBackground() self.timer = None self.env_thread = None
from PySide2.QtCore import QFile, Slot from PySide2.QtUiTools import QUiLoader class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__() @Slot() def alert(self): alert = QMessageBox() alert.setText(self.text_field.text()) alert.exec_() @Slot() def quit(self): quit() if __name__ == '__main__': app = QApplication([]) loader = QUiLoader() loader.registerCustomWidget(Dialog) base_dir = os.path.dirname(os.path.realpath(__file__)) dialog = loader.load(os.path.join(base_dir, 'alert-quit.ui')) dialog.show() app.exec_()
Qt.KeepAspectRatio) self.release_cover.setPixmap(scaled_pix) def sort_indicator_changed(self, index, order): del order if index == 0: self.collection_list.horizontalHeader().setSortIndicator( self.collection_list.model().sort_column, self.collection_list.model().sort_order) @Slot() def show_settings(self): settings_window = settings.create_dialog(self) settings_window.setup() settings_window.exec_() if __name__ == "__main__": app = QApplication(sys.argv) ui_file = QFile("disco.ui") ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(DiscoMainWindow) window = loader.load(ui_file) ui_file.close() window.populate() window.show() sys.exit(app.exec_())
def buildGui(self): ui_file_loader = QUiLoader() ui_file_loader.registerCustomWidget(ResizeStackWidget) ui_file_loader.registerCustomWidget(ConditionalWizard) main_ui_file = QFile("ui/main_wizard.ui") main_ui_file.open(QFile.ReadOnly) self._window = ui_file_loader.load(main_ui_file) main_ui_file.close() # def fc(type, name): return self._window.findChild(type, name) def fc_l(name): return fc(QLineEdit, name) def fc_b(name): return fc(QPushButton, name) def fc_cb(name): return fc(QComboBox, name) def fc_p(name): l = fc_l(name + "_lineEdit") b = fc_b(name + "_pushButton") if l is None: raise Exception("lineEdit {}_lineEdit not found".format(name)) if b is None: raise Exception( "pushButton {}_pushButton not found".format(name)) return [l, b] # page 0 self.__operation_cb = fc_cb("operation_comboBox") self.__operation_cb.currentIndexChanged.connect(self.onOperationSelect) self.__source_rsw = fc(ResizeStackWidget, "source_stackedWidget") self.__sink_rsw = fc(ResizeStackWidget, "sink_stackedWidget") self.__datasource_stm = STM32CubeMX_DataSource(self._window, fc_p("source_stm")) self.__datasource_eagle = AutodeskEagle_DataSource( self._window, fc_p("source_eagle_sch"), fc_p("source_eagle_ic")) self.__datasink_stm = STM32CubeMX_DataSink(self._window, fc_p("sink_stm")) self.__datasink_eagle = AutodeskEagle_DataSink(self._window, fc_p("sink_eagle_sch"), fc_p("sink_eagle_brd"), fc_p("sink_eagle_ic")) self._window.registerCallback(self.onPageChanged) # page 1 self.__changelog_model = QStandardItemModel() self.__error_model = QStandardItemModel() self.__changelog_tableView = fc(QTableView, "changelog_tableView") self.__changelog_tableView.setModel(self.__changelog_model) self.__error_tableView = fc(QTableView, "error_tableView") self.__error_tableView.setModel(self.__error_model) # page 2 self.__target_rsw = fc(ResizeStackWidget, "target_stackedWidget") self.__datatarget_stm = STM32CubeMX_DataTarget(self._window, fc_p("target_stm")) self.__datatarget_eagle = AutodeskEagle_DataTarget( self._window, fc_p("target_eagle_sch"), fc_p("target_eagle_brd")) self.config_by_idx = { # operation idx # stm => eagle 0: ConfigEntry(source_rsw_idx=0, sink_rsw_idx=1, target_rsw_idx=1, source_input=self.__datasource_stm, sink_input=self.__datasink_eagle, target_input=self.__datatarget_eagle), # eagle => stm 1: ConfigEntry(source_rsw_idx=1, sink_rsw_idx=0, target_rsw_idx=0, source_input=self.__datasource_eagle, sink_input=self.__datasink_stm, target_input=self.__datatarget_stm) } self.__operation_cb.setCurrentIndex(0) self.onOperationSelect(0)
def __init__(self, ui_file, parent=None): super(MainWindow, self).__init__(parent) ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) self.compartment_list = list() # Empty compartment_list initialized self.variable_list = list() # Empty variable list initialized self.simulation = None # Simulation is generated after compilation self.substitutions = dict() # Substitutions come from exec code loader = QUiLoader() loader.registerCustomWidget( QTableWidgetDragRows ) # Register custom QTableWidgetDragRows for Drag and Right-Click functions self.window = loader.load(ui_file) ui_file.close() plt.rc('text', usetex=True ) # set matplotlib options so that it uses LaTeX formatting plt.rc('font', family='serif') # Find buttons and link them to the respective functions, signals and options action_save_digraph = self.window.findChild(QAction, 'actionSaveDigraph') action_save_digraph.triggered.connect(self.save_digraph_event) action_save_plot = self.window.findChild(QAction, 'actionSavePlot') action_save_plot.triggered.connect(self.save_plot_event) add_compartment_button = self.window.findChild(QPushButton, 'AddCompartmentButton') add_compartment_button.clicked.connect( self.open_add_compartment_dialog) add_variable_button = self.window.findChild(QPushButton, 'AddVariableButton') add_variable_button.clicked.connect(self.open_add_variable_dialog) compile_button = self.window.findChild(QPushButton, 'CompileButton') compile_button.clicked.connect(self.compile) run_simulation_button = self.window.findChild(QPushButton, 'SimulateButton') run_simulation_button.clicked.connect(self.open_run_simulation) show_r0_button = self.window.findChild(QPushButton, 'R0Button') show_r0_button.clicked.connect(self.show_r0) self.compartment_table = self.window.findChild(QTableWidgetDragRows, 'CompartmentTable') self.compartment_table.setEditableInfectionState(True) self.compartment_table.delItem.connect(self.remove_item) self.compartment_table.editIS.connect(self.toggle_is) self.compartment_table.dropSignal.connect(self.drop_event) self.variable_table = self.window.findChild(QTableWidgetDragRows, 'VariableTable') self.variable_table.setDragEnabled( False) # Set this table to be undraggable self.variable_table.delItem.connect(self.remove_item) self.vital_dynamics_checkbox = self.window.findChild( QCheckBox, 'VitalDynamicsCheckBox') self.vital_dynamics_checkbox.stateChanged.connect( self.vital_dynamics_toggle) self.diagram_view = self.window.findChild( QGraphicsView, 'DiagramView') # Diagram for NetworkX Graph self.logging_view = self.window.findChild( QGraphicsView, 'LoggingView') # Console for Logging progress self.timeLE = self.window.findChild(QLineEdit, 'TimeLE') self.timeLE.setValidator(QIntValidator( )) # Validator to ensure only integers are placed in Time LineEdit self.window.setWindowIcon(QIcon(os.path.join( 'ui_files', 'icon.png'))) # Set the window icon self.window.show()
setColorImage(editorWindow) setDepthImage(editorWindow) setAOImage(editorWindow) setFinalImage(editorWindow) loadEditor() if __name__ == "__main__": settings.init() app = QApplication(sys.argv) ui_focusfile = QFile("depth.ui") ui_focusfile.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(FocusWidget) focusWindow = loader.load(ui_focusfile) connectFuncFocus(focusWindow) ui_editorfile = QFile("interfaceTest.ui") ui_editorfile.open(QFile.ReadOnly) loader = QUiLoader() editorWindow = loader.load(ui_editorfile) connectFuncEditor(editorWindow) ui_Mainfile = QFile("menu.ui") ui_Mainfile.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(QVideoWidget) mainWindow = loader.load(ui_Mainfile) setTreeView(mainWindow)
def __init__(self): loader = QUiLoader() loader.registerCustomWidget(MplWidget) self.ui_viewall = loader.load('UIs/viewall.ui') self.ui_viewall.show()
# load reference data with open("guids.json", "r") as g: guid_dict = json.loads(g.read()) try: # find the install path for the steam version steam_reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam") steam_path = winreg.QueryValueEx(steam_reg, "SteamPath")[0] steam_path += "/steamapps/common/Deep Rock Galactic/FSD/Saved/SaveGames" except: steam_path = "." # load the UI and do a basic check loader = QUiLoader() loader.registerCustomWidget(TextEditFocusChecking) widget = loader.load(ui_file, None) ui_file.close() if not widget: print(loader.errorString()) sys.exit(-1) # connect file opening function to menu item widget.actionOpen_Save_File.triggered.connect(open_file) # set column names for overclock treeview widget.overclock_tree.setHeaderLabels(["Overclock", "Status", "GUID"]) # populate the promotion drop downs promo_boxes = [ widget.driller_promo_box, widget.gunner_promo_box,
class QtFrontend(ViewSBFrontend): """ Qt Frontend that consumes packets for display. """ UI_NAME = 'qt' UI_DESCRIPTION = 'unstable GUI in Qt' # So, Qt's tree widgets require that column 0 have the expand arrow, but you _can_ change # where column 0 is displayed. # We want the summary column to have the expand arrow, so we'll swap it # with the timestamp column in __init__(). COLUMN_TIMESTAMP = 5 COLUMN_DEVICE = 1 COLUMN_ENDPOINT = 2 COLUMN_DIRECTION = 3 COLUMN_LENGTH = 4 COLUMN_SUMMARY = 0 COLUMN_STATUS = 6 COLUMN_DATA = 7 @staticmethod def reason_to_be_disabled(): try: import PySide2 except ImportError: return "PySide2 (Qt library) not available." return None @staticmethod def _stringify_list(lst): """ Tiny helper than runs the str constructor on every item in a list, but specifically handles two cases: 1) the object in question is None, which we instead want to display as an empty string, 2) the resulting string contains a null character, which Qt doesn't like, so we'll represent it to the user as, literally, \0. """ return [ str(x).replace('\0', r'\0') if x is not None else '' for x in lst ] def _create_item_for_packet(self, viewsb_packet): """ Creates a QTreeWidgetItem for a given ViewSBPacket. Args: viewsb_packet -- The ViewSBPacket to create the QTreeWidgetItem from. Returns a QTreeWidgetItem. """ def get_packet_string_array(viewsb_packet): """ Tiny helper to return and stringify the common fields used for the columns of tree items. """ direction = viewsb_packet.direction.name if viewsb_packet.direction is not None else '' length = len( viewsb_packet.data) if viewsb_packet.data is not None else '' return self._stringify_list([ viewsb_packet.summarize(), viewsb_packet.device_address, viewsb_packet.endpoint_number, direction, length, viewsb_packet.timestamp, viewsb_packet.summarize_status(), viewsb_packet.summarize_data() ]) + [viewsb_packet] item = QTreeWidgetItem(get_packet_string_array(viewsb_packet)) # Give the item a reference to the original packet object. item.setData(0, QtCore.Qt.UserRole, viewsb_packet) return item def _recursively_walk_packet(self, viewsb_packet): """ Recursively walks packet subordinates, batching QTreeWidgetItem.addChildren as much as possible. Args: viewsb_packet -- The top-level packet (as far as the caller's context is concerned). """ packet_item = self._create_item_for_packet(viewsb_packet) packet_children_list = [] for sub_packet in viewsb_packet.subordinate_packets: # Create the item for this packet, and recursively fill its children. packet_children_list.append( self._recursively_walk_packet(sub_packet)) packet_item.addChildren(packet_children_list) return packet_item def __init__(self): """ Sets up the Qt UI. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) signal.signal( signal.SIGINT, signal.SIG_DFL) # fix SIGINT handling - cleanly exit on ctrl+c self.app = QApplication([]) self.ui_file = QtCore.QFile( os.path.dirname(os.path.realpath(__file__)) + '/qt.ui') self.loader = QUiLoader() self.loader.registerCustomWidget(ViewSBQTreeWidget) self.loader.registerCustomWidget(ViewSBHexView) self.window = self.loader.load(self.ui_file) # type: QMainWindow # Swap columns 0 and 5 to put the expand arrow on the summary column. self.window.usb_tree_widget.header().swapSections(0, 5) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_TIMESTAMP, 120) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DEVICE, 32) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_ENDPOINT, 24) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DIRECTION, 42) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_LENGTH, 60) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_SUMMARY, 500) self.window.update_timer = QtCore.QTimer() self.window.update_timer.timeout.connect(self._update) self.window.usb_tree_widget.currentItemChanged.connect( self._tree_current_item_changed) self.window.usb_tree_widget = self.window.usb_tree_widget self.window.usb_tree_widget.sortByColumn(0) self.window.showMaximized() def _update(self): """ Called by the QTimer `update_timer`; collects packets the queue and adds them to the tree view. We use this instead of calling `handle_communications` and defining `handle_incoming_packet`, because adding items one at a time as we receive them is slower than batching them. Note: Since this is called via a QTimer signal, this method runs in the UI thread. """ # If the process manager told us to stop (which might happen if e.g. the backend exits), # then stop and exit. if self.termination_event.is_set(): self.app.closeAllWindows() packet_list = [] try: # Get as many packets as we can as quick as we can. while True: packet = self.data_queue.get_nowait() packet_list.append(packet) # But the instant it's empty, don't wait for any more; just send them to be processed. except multiprocessing.queues.Empty: pass finally: self.add_packets(packet_list) def _tree_current_item_changed(self, current_item, _previous_item): """ Handler for the QTreeWidget.currentItemChanged() signal that populates the side panels with detail fields and a hex representation of the current packet. """ # Clear the details widget. self.window.usb_details_tree_widget.clear() current_packet = current_item.data(0, QtCore.Qt.UserRole) # A list of 2-tuples: first element is a table title, and the second is usually a string:string dict. detail_fields = current_packet.get_detail_fields() if detail_fields: self.update_detail_fields(detail_fields) self.window.usb_hex_view.populate(current_packet.get_raw_data()) def update_detail_fields(self, detail_fields): """ Populates the detail view with the relevant fields for the selected packet. """ # Each table will have a root item in the details view. root_items = [] for table in detail_fields: title = table[0] root = QTreeWidgetItem([title]) children = [] fields = table[1] # The usual case: a str:str dict. if isinstance(fields, dict): for key, value in fields.items(): children.append( QTreeWidgetItem(self._stringify_list([key, value]))) # Sometimes it'll just be a 1-column list. elif isinstance(fields, list): for item in fields: children.append( QTreeWidgetItem(self._stringify_list([item]))) # Sometimes it'll just be a string, or a `bytes` instance. else: children.append(QTreeWidgetItem(self._stringify_list([fields ]))) root.addChildren(children) # Add an empty "item" between each table. root_items.extend([root, QTreeWidgetItem([])]) self.window.usb_details_tree_widget.addTopLevelItems(root_items) self.window.usb_details_tree_widget.expandAll() self.window.usb_details_tree_widget.resizeColumnToContents(0) self.window.usb_details_tree_widget.resizeColumnToContents(1) def add_packets(self, viewsb_packets): """ Adds a list of top-level ViewSB packets to the tree. We're in the UI thread; every bit of overhead counts, so let's batch as much as possible. """ top_level_items_list = [] for viewsb_packet in viewsb_packets: # Create the item for this packet, and recursively fill its children. top_level_items_list.append( self._recursively_walk_packet(viewsb_packet)) self.window.usb_tree_widget.addTopLevelItems(top_level_items_list) def run(self): """ Overrides ViewSBFrontend.run(). """ # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer? self.window.update_timer.start(100) self.app.exec_() self.stop() def stop(self): self.app.closeAllWindows() self.termination_event.set()
def __init__(self): QObject.__init__(self) self.module_path = os.path.dirname(__file__) self.tables = [] self.series_dict = dict() n_cpu_cores = cpu_count() print("number of cpu cores: ", n_cpu_cores) self.pool = Pool(processes=n_cpu_cores) self.coins = Coins(self.pool) self.model = Model() self.chart = QtCharts.QChart() self.callout = Callout(self.chart) self.callout.hide() # loading widgets from designer file loader = QUiLoader() loader.registerCustomWidget(QtCharts.QChartView) self.window = loader.load(self.module_path + "/ui/application_window.ui") main_frame = self.window.findChild(QFrame, "main_frame") chart_frame = self.window.findChild(QFrame, "chart_frame") chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame") button_read_tags = self.window.findChild(QPushButton, "button_read_tags") button_save_matrix = self.window.findChild(QPushButton, "button_save_matrix") button_save_image = self.window.findChild(QPushButton, "button_save_image") button_reset_zoom = self.window.findChild(QPushButton, "button_reset_zoom") self.table_view = self.window.findChild(QTableView, "table_view") self.chart_view = self.window.findChild(QtCharts.QChartView, "chart_view") self.label_mouse_coords = self.window.findChild( QLabel, "label_mouse_coords") self.table_view.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.table_view.verticalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.table_view.setModel(self.model) # signal connection button_read_tags.clicked.connect(self.read_tags) button_save_matrix.clicked.connect(self.save_matrix) button_save_image.clicked.connect(self.save_image) button_reset_zoom.clicked.connect(self.reset_zoom) self.table_view.selectionModel().selectionChanged.connect( self.selection_changed) self.coins.new_spectrum.connect(self.on_new_spectrum) self.model.dataChanged.connect(self.data_changed) # Creating QChart self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations) self.chart.setTheme(QtCharts.QChart.ChartThemeLight) self.chart.setAcceptHoverEvents(True) self.axis_x = QtCharts.QValueAxis() self.axis_x.setTitleText("Energy [keV]") self.axis_x.setRange(0, 100) self.axis_x.setLabelFormat("%.0f") self.axis_y = QtCharts.QValueAxis() self.axis_y.setTitleText("Intensity [a.u.]") self.axis_y.setRange(0, 100) self.axis_y.setLabelFormat("%d") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.chart_view.setChart(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand) # custom stylesheet style_file = QFile(self.module_path + "/ui/custom.css") style_file.open(QFile.ReadOnly) self.window.setStyleSheet(style_file.readAll().data().decode("utf-8")) style_file.close() # effects main_frame.setGraphicsEffect(self.card_shadow()) chart_frame.setGraphicsEffect(self.card_shadow()) chart_cfg_frame.setGraphicsEffect(self.card_shadow()) button_read_tags.setGraphicsEffect(self.button_shadow()) button_save_matrix.setGraphicsEffect(self.button_shadow()) button_save_image.setGraphicsEffect(self.button_shadow()) button_reset_zoom.setGraphicsEffect(self.button_shadow()) self.window.show()