def _init_ui(self): h_layout = QHBoxLayout() h_layout.addWidget(self.info_ico_lbl) h_layout.addWidget(self.lib_selector, 1) dummy = QWidget() dummy.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.toolbar.addWidget(dummy) self.toolbar.addActions([ self.refresh_action, self.edit_action, self.delete_action, self.add_action ]) self.toolbar.setContentsMargins(0, 0, 0, 0) self.toolbar.setIconSize(QSize(16, 16)) layout = QVBoxLayout() layout.setContentsMargins(5, 0, 0, 0) layout.setMenuBar(self.toolbar) layout.addLayout(h_layout) layout.addWidget(self.info_lbl) layout.addWidget(self.group_manager) layout.addWidget(self.treeView, 1) container = QWidget() container.setLayout(layout) self.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetClosable) self.setWidget(container) self.setWindowTitle("Library Manager") if self.lib_selector.count() > 0: self._lib_changed()
def __init__(self): super(Dialog, self).__init__() self.createMenu() self.createHorizontalGroupBox() self.createGridGroupBox() self.createFormGroupBox() bigEditor = QTextEdit() bigEditor.setPlainText("This widget takes up all the remaining space " "in the top-level layout.") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(self.gridGroupBox) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Basic Layouts")
def __init__(self): super(Dialog, self).__init__() self.createMenu() self.widget_register_url() self.widget_download() self.thread_download = threading.Thread( group=None, target=self.run_downloader, name=None, args=(), kwargs={}, daemon=True ) self.running = False bigEditor = QTextEdit() bigEditor.setPlainText("This widget takes up all the remaining space " "in the top-level layout.") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.form_register_url) mainLayout.addWidget(self.form_download_urls) self.setLayout(mainLayout) self.setWindowTitle("Bamboodl")
def __init__(self, extra, synth, decoders, set_decoder): super(Dialog, self).__init__() self.synth = synth self.decoders = decoders self.set_decoder = set_decoder self.createMenu() self.createAudioControls() self.createDatasetControls() self.createGridGroupBox() mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) vLayout = QVBoxLayout() vLayout.addWidget(self.audioControls) # vLayout.addWidget(self.datasetControls) vLayout.addWidget(self.gridGroupBox) hLayout = QHBoxLayout() vGroupBox = QGroupBox() vGroupBox.setLayout(vLayout) hLayout.addWidget(vGroupBox) hLayout.addWidget(extra) hGroupBox = QGroupBox() hGroupBox.setLayout(hLayout) hGroupBox.setFlat(True) title = QLabel("Sounderfeit") title.setStyleSheet("font-size: 20pt; font-weight: bold;") mainLayout.addWidget(title) mainLayout.addWidget(hGroupBox) self.setLayout(mainLayout) self.setWindowTitle("Sounderfeit")
def __init__(self, mw, parent=None): super(ImageDisp, self).__init__(parent) self.MW = mw QApplication.setStyle(QStyleFactory.create("Fusion")) QApplication.setPalette(QApplication.style().standardPalette()) self.file_filter = ("PNG files (*.png);;All files (*)") self.setWindowFlag(Qt.Window, True) self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.scrollArea.setAlignment(Qt.AlignLeft| Qt.AlignTop) central = QVBoxLayout() self.tb = QToolBar() central.setMenuBar(self.tb) central.addWidget(self.scrollArea) self.setLayout(central) self.resize(930,400) self.createActions() self.createToolBar()
def __init__(self, parent=None): super(ConfigDialog, self).__init__(parent) self.contentsWidget = QListWidget() self.contentsWidget.setViewMode(QListView.IconMode) self.contentsWidget.setIconSize(QSize(96, 84)) self.contentsWidget.setMovement(QListView.Static) self.contentsWidget.setMaximumWidth(128) self.contentsWidget.setSpacing(12) self.createIcons() closeButton = QPushButton("Close") closeButton.clicked.connect(self.close) # horizontalLayout = QHBoxLayout() # horizontalLayout.addWidget(self.contentsWidget) # horizontalLayout.addWidget(self.pagesWidget, 1) buttonsLayout = QHBoxLayout() buttonsLayout.addStretch(1) buttonsLayout.addWidget(closeButton) mainLayout = QVBoxLayout() mainLayout.addWidget(self.contentsWidget, Qt.AlignCenter) mainLayout.addStretch(1) mainLayout.addSpacing(12) mainLayout.addLayout(buttonsLayout) self.setLayout(mainLayout) self.setWindowTitle("Config Dialog") menuBar = QMenuBar(self) # group.setExclusive(True) ## 只允许一个 menu = menuBar.addMenu("&About") menu.addAction('about', lambda: QApplication.instance().aboutQt()) mainLayout.setMenuBar(menuBar)
def __init__(self): super(Dialog, self).__init__() self.createMenu() self.createHorizontalGroupBox() self.createGridGroupBox() self.createFormGroupBox() bigEditor = QTextEdit() bigEditor.setPlainText("This widget takes up all the remaining space " "in the top-level layout.") buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(self.gridGroupBox) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Basic Layouts")
def __init__(self, parent=None): super(myWindow, self).__init__() self.setWindowFlags(self.windowFlags() | Qt.WindowMinMaxButtonsHint) self.resize(600, 400) self._imagLoader = imageLoader(self) self._scroll = QScrollArea(self) # self._scroll.setWidgetResizable(True) self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._scroll.setAlignment(Qt.AlignCenter) self._scroll.setStyleSheet(strStyle) self._widget = myPaint(self) self._widget.resize(1000, 1000) self._widget.setFocusPolicy(Qt.WheelFocus) hLay = QHBoxLayout(self._widget) self._widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self._scroll.setWidget(self._widget) self._scroll.installEventFilter(self) self._widget.installEventFilter(self) main_lay = QVBoxLayout(self) main_lay.addWidget(self._scroll) hlay = QHBoxLayout() self.btn_about = QPushButton("aboutQt", self) self.btn_pause = QPushButton("Pause", self) self.btn_cancel = QPushButton("Cancel", self) hlay.addStretch() hlay.addWidget(self.btn_pause) hlay.addWidget(self.btn_about) hlay.addWidget(self.btn_cancel) main_lay.addLayout(hlay) menuBar = QMenuBar(self) group = QActionGroup(self) # group.setExclusive(True) ## 只允许一个 menu = menuBar.addMenu("DlgMenu") act1 = group.addAction(QAction('111')) act2 = group.addAction(QAction('222')) act3 = group.addAction(QAction('333')) menu.addAction(act1) menu.addAction(act2) menu.addAction(act3) for i in range(1, 4): str = 'act%d.setCheckable(True)' % i eval(str) str = 'act%d.setChecked(True)' % i eval(str) # act1.setChecked(True) main_lay.setMenuBar(menuBar) self.btn_about.clicked.connect( lambda: QApplication.instance().aboutQt()) self.btn_pause.clicked.connect(self.on_PauseClick) self.btn_cancel.clicked.connect(lambda: self.reject()) self._imagLoader.evt_showImg.connect(self._widget.on_paint) self._imagLoader.finished.connect(self._imagLoader.deleteLater) QTimer.singleShot(0, lambda: self._imagLoader.start())
def __init__(self, handler=None): QWidget.__init__(self) self.handler = handler self.canvas = Plotter(self, handler=self, plotterType=PlotterType.READING) graphToolBar = NavigationToolbar(self.canvas, self) graphToolBar.setMovable(False) dockLayout = QVBoxLayout() dockLayout.setMenuBar(graphToolBar) self.setLayout(dockLayout) self.layout().addWidget(self.canvas) self.loadedData = [] self.loadedEvents = []
def __init__(self): super().__init__() self.createMenu() self.createHorGroupBox() self.createGridGroupBox() self.initUI() mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.horGroupBox) mainLayout.addWidget(self.gridGroupBox) self.setLayout(mainLayout)
def initUI(self): #GrBox1 GrBox = QGroupBox() vbox = QHBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) #GrBox.setFixedHeight(60) pathButton = QPushButton(QIcon('icons\\pack.png'), "Папка") pathButton.setIconSize(QSize(25, 25)) pathButton.setVisible(True) pathLable = QLineEdit() #pathLable.setReadOnly(True) subPathCheck = QCheckBox() subPathCheck.setText("Подпапки") subPathCheck.setCheckState(0) vbox.addWidget(pathLable) vbox.addWidget(subPathCheck) vbox.addWidget(pathButton) GrBox.setLayout(vbox) #/GrBox1 #FilesTable FilesTable = QListView(self) FilesTable.setToolTip( "Список файлов, выберите нужные файлы для обработки,\nдля просмотра файла дважды щелкните по нему" ) FilesTableModel = QStandardItemModel() FilesTable.setModel(FilesTableModel) #/FilesTable #mainLayout mainLayout = QVBoxLayout() mainLayout.setContentsMargins(0, 0, 0, 0) mainLayout.setMenuBar(GrBox) mainLayout.addWidget(FilesTable) #/mainLayout #self self.setLayout(mainLayout) self.path = pathLable.text() self.pathLable = pathLable self.subPathCheck = subPathCheck self.FilesTableModel = FilesTableModel #/self #connections pathLable.textChanged.connect(self.setPath) pathButton.clicked.connect(self.selectPath) subPathCheck.clicked.connect(self.setPath) FilesTableModel.itemChanged.connect(self.ChangeFilesList) FilesTable.doubleClicked.connect(self.openFile)
def __init__(self): super(UiDialog, self).__init__() self.createMenu() self.createGridGroupBox() self.createPlotFrame() self.create_pop_box() mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.resultFrame) mainLayout.addWidget(self.pop_frame) mainLayout.addWidget(self.plotFrame) self.setLayout(mainLayout) self.setWindowTitle("Setup control")
def initUI(self): #GrBox1 GrBox=QGroupBox() vbox = QHBoxLayout(self) vbox.setContentsMargins(0,0,0,0) #GrBox.setFixedHeight(60) pathButton = QPushButton(QIcon('icons\\pack.png'),"Папка") pathButton.setIconSize(QSize(25,25)) pathButton.setVisible(True) pathLable=QLineEdit() #pathLable.setReadOnly(True) subPathCheck=QCheckBox() subPathCheck.setText("Подпапки") subPathCheck.setCheckState(0) vbox.addWidget(pathLable) vbox.addWidget(subPathCheck) vbox.addWidget(pathButton) GrBox.setLayout(vbox) #/GrBox1 #FilesTable FilesTable=QListView(self) FilesTable.setToolTip("Список файлов, выберите нужные файлы для обработки,\nдля просмотра файла дважды щелкните по нему") FilesTableModel = QStandardItemModel() FilesTable.setModel(FilesTableModel) #/FilesTable #mainLayout mainLayout = QVBoxLayout() mainLayout.setContentsMargins(0,0,0,0) mainLayout.setMenuBar(GrBox) mainLayout.addWidget(FilesTable) #/mainLayout #self self.setLayout(mainLayout) self.path=pathLable.text() self.pathLable=pathLable self.subPathCheck=subPathCheck self.FilesTableModel = FilesTableModel #/self #connections pathLable.textChanged.connect(self.setPath) pathButton.clicked.connect(self.selectPath) subPathCheck.clicked.connect(self.setPath) FilesTableModel.itemChanged.connect(self.ChangeFilesList) FilesTable.doubleClicked.connect(self.openFile)
def __init__(self): super(stopwatch, self).__init__() self.createMenu() self.start_button = QPushButton("Start", self) self.reset_button = QPushButton("Reset", self) self.int_button = QPushButton("Int", self) self.setGeometry(200, 200, 450, 220) self.setWindowTitle("StopWatch") self.table = QTableWidget(self) self.table.setColumnCount(1) self.table.setRowCount(100) self.LCD = QLCDNumber(self) self.gridGroupBox = QGroupBox() self.grid = QGridLayout() self.grid.addWidget(self.LCD, 0, 0, 1, 3) self.grid.addWidget(self.table, 0, 3, 0, 3) self.grid.setRowMinimumHeight(0, 200) self.grid.addWidget(self.start_button, 1, 0) self.grid.addWidget(self.int_button, 1, 1) self.grid.addWidget(self.reset_button, 1, 2) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) self.gridGroupBox.setLayout(self.grid) mainLayout.addWidget(self.gridGroupBox) self.setLayout(mainLayout) self.LCD.setDigitCount(12) self.time = 0 self.ms = 0 self.sec = 0 self.min = 0 self.hour = 0 self.rezults = 0 self.LCD.display("00:00:00:00") self.timer = QTimer() self.timer.setInterval(10) self.timer.timeout.connect(self.display) self.start_button.clicked.connect(self.start) self.reset_button.clicked.connect(self.reset) self.int_button.clicked.connect(self.int_)
class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() self.menu = MenuBar(self) self.latexEdit = LatexEdit(self) self.initLayout() def initUI(self): self.setMinimumSize(1200, 240) self.setMaximumSize(1600, 340) self.setWindowTitle("化学方程式配平器") self.show() def initLayout(self): self.layout = QVBoxLayout(self) self.layout.addWidget(self.latexEdit.canvas) self.layout.setContentsMargins(30, 30, 30, 30) self.layout.setMenuBar(self.menu) def balance(self): self.latexEdit.setLatex(balance.balance(self.latexEdit.text())) def generateExample(self): self.latexEdit.setLatex(balance.getExample()) def insert(self, string): self.latexEdit.setLatex(self.latexEdit.text() + string) def insertCharge(self): charge, ok = QInputDialog.getInt(self, "插入电荷", "请输入要插入的电荷数:", QLineEdit.Normal) if ok: text = f"[{abs(charge)}{(charge>0 and '+' or '-')}]" self.insert(text) def editSource(self): newText, ok = QInputDialog.getText(self, "编辑源文本", "请输入修改后的源文本:", QLineEdit.Normal, self.latexEdit.text()) if ok: self.latexEdit.setText(newText) def keyPressEvent(self, event): eventKey = event.key() if eventKey == Qt.Key_Return or eventKey == Qt.Key_Enter: self.balance()
class Containers(QWidget): """ Containers QtWidget. Attributes: :__layout (QVBoxLayout): :__toolbar (Toolbar): """ def __init__(self, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.__layout = QVBoxLayout() self.__toolbar = Toolbar() self.__table = Table() self.__show_all = ShowAll() SignalDispatcher.register_signal('containers_dock.toggle_show_all', self.__show_all.clicked) def build(self): """ Builds the interface. :return: """ self.__layout.setMenuBar(self.__toolbar) self.__toolbar.build() self.__layout.addWidget(self.__table) self.__table.build() self.__layout.addWidget(self.__show_all) self.setLayout(self.__layout) @property def toolbar(self): return self.__toolbar @property def table(self): return self.__table @property def show_all(self): return self.__show_all
def initUI(self): self.connection_config = ConnectionConfig(self) self.connection_config.changed.connect(self.worker.setParameters) self.connection_config.changed.connect(self.setParameters) self.connection_config.restoreSettings(self.settings, DEFAULT_PARAMETERS) self.startButton = QPushButton(QIcon.fromTheme("media-playback-start"), "Start") self.stopButton = QPushButton(QIcon.fromTheme("media-playback-stop"), "Stop") self.restartButton = QPushButton( QIcon.fromTheme("media-skip-backward"), "Restart") self.startButton.clicked.connect(self.onStartClicked) self.stopButton.clicked.connect(self.onStopClicked) self.restartButton.clicked.connect(self.onRestartClicked) self.worker.received.connect(self.onReceived) self.worker.error.connect(self.onError) self.worker.running_changed.connect(self.update_status) hbox = QHBoxLayout() hbox.addWidget(self.connection_config) hbox.addWidget(self.startButton) hbox.addWidget(self.stopButton) hbox.addWidget(self.restartButton) self.treeView = HttpMessagesTreeView(self.plugin_registry, self) self.treeView.selected.connect(self.onMessageSelected) self.tabs = HttpMessagesTabs(self.plugin_registry) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.treeView) vbox.addWidget(self.tabs) self.setLayout(vbox) vbox.setMenuBar(self.createMenu(QMenuBar())) self.show() self.update_status(self.worker.status()) self.onMessageSelected(None)
def __init__(self, screen, parent=None): super(Dialog, self).__init__(parent=parent) # init self._query_val = [] self._query_str = '' self.log_results = [] self._limit = '1000' self._count = 0 # screen related if screen: screen_temp = screen.size() self.screen_width = screen_temp.width() self.screen_height = screen_temp.height() print('App is shown in ' + screen.name()) print('Size: %d x %d' % (self.screen_width, self.screen_height)) self.border_left = (self.screen_width - self.window_width) * 0.5 self.border_top = (self.screen_height - self.window_width) * 0.5 else: self.border_left = self.def_border_left self.border_top = self.def_border_top # build menu and actions for the menu self.create_actions() self.create_query_actions_fast() self.create_menu() self.create_query_box() self.create_result_box() # build the layout (use grid) main_layout = QVBoxLayout() main_layout.setMenuBar(self.menuBar) main_layout.addWidget(self.qu_box) main_layout.addWidget(self.res_box) main_layout.addLayout(self.result_buttons) self.setLayout(main_layout) # 4. Adjust the top app layout dimension self.setGeometry(self.border_left, self.border_top, self.window_width, self.window_height) self.setWindowTitle('ADAS DB Finder 0.1') self.setWindowIcon(QIcon('icon\sql.png'))
def __init__(self): super(QMW, self).__init__() self.tableau = TableauQt("x") self.simple = False # doit-on faire un tableau simplifié # symboles unicode 2a7d et 2a7e voir # http://fr.wikipedia.org/wiki/Table_des_caract%C3%A8res_Unicode_%282000-2FFF%29#Fl.C3.A8ches self.inequations = {"⩽0": "-0", "<0": "--", "⩾0": "+0", ">0": "++"} self.createMenu() self.createHorizontalGroupBox() self.createFormGroupBox() self.createBoundBox() self.createSolutionBox() self.exitAct = QAction( "E&xit", self, shortcut="Ctrl+Q", statusTip="Sortir de l'application", triggered=self.close ) bigEditor = QTextEdit() bigEditor.setPlainText("Création de la sortie latex ici pour un copier/coller ") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) # | QDialogButtonBox.Cancel buttonBox.accepted.connect(self.close) widget = QWidget() self.setCentralWidget(widget) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(self.BoundBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(self.solGroupBox) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(buttonBox) widget.setLayout(mainLayout) self.bigEditor = bigEditor self.setWindowTitle("Tableau de signe")
def __init__(self): # Constructor de clase para la interfaz grafica super().__init__() caja_v = QVBoxLayout() caja_regex = QHBoxLayout() menu_bar = QMenuBar() menu_bar.addAction("About", self.about) self.txt_regex = QLineEdit() self.txt_a_tratar = QPlainTextEdit() self.txt_coincidencias = QPlainTextEdit() btn_probar = QPushButton("Probar") caja_regex.addWidget(QLabel("Expresión:")) caja_regex.addWidget(self.txt_regex) caja_regex.addWidget(btn_probar) self.chk_case = QCheckBox("Mayúsculas") caja_opciones = QHBoxLayout() caja_opciones.addWidget(QLabel("Texto a tratar:")) caja_opciones.addStretch(1) caja_opciones.addWidget(self.chk_case) caja_v.setMenuBar(menu_bar) caja_v.addLayout(caja_regex) caja_v.addLayout(caja_opciones) caja_v.addWidget(self.txt_a_tratar) caja_v.addWidget(QLabel("Coincidencias:")) caja_v.addWidget(self.txt_coincidencias) btn_probar.pressed.connect(self.evaluar) self.txt_regex.pyqtConfigure(clearButtonEnabled=True) self.txt_regex.pyqtConfigure(placeholderText="Inserte su regex") self.txt_regex.textEdited.connect(self.reset) self.txt_a_tratar.pyqtConfigure(placeholderText="Insete su texto a tratar") self.txt_coincidencias.setReadOnly(True) self.setLayout(caja_v) self.setWindowTitle("Evaluador de RegEx") self.setWindowIcon(QIcon("zorro.png")) self.resize(400, 350) self.centrar() self.show()
def __init__(self, parent=None): super(Window, self).__init__(parent) with open('./features_extracted.json', 'r') as file: self.loaded_json_data = json.load(file) self.figures = [] self.canvases = [] self.toolbars = [] self.brainStateLabels = [] self.accuracyLabels = [] self.axes = [] self.tabs = [] self.tabs = QTabWidget() # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the plot or (figure) self.canvas = FigureCanvas(self.figure) self.openFileDialog() # this is the Navigation Toolbar for the top of the plot self.toolbar = NavigationToolbar(self.canvas, self) # create the layout and menu layout = QVBoxLayout() menu_bar = QMenuBar() fileMenu = menu_bar.addMenu('File') importDataAction = QAction('Import Data', self) importDataAction.setShortcut('Ctrl+I') importDataAction.triggered.connect(self.openFileDialog) fileMenu.addAction(importDataAction) layout.setMenuBar(menu_bar) layout.addWidget(self.toolbar) layout.addWidget(self.canvas) outputHBox = QHBoxLayout() # create the labels that we will need to access again self.brainStateLabel = QLabel("Brain State : ") self.brainStateLabel.setFixedSize(200, 20) self.accuracyLabel = QLabel("Accuracy of Prediction: ") self.accuracyLabel.setFixedSize(400, 20) predictionStatisticsVBoxLeft = QVBoxLayout() predictionStatisticsVBoxLeft.addWidget(self.brainStateLabel) predictionStatisticsVBoxRight = QVBoxLayout() predictionStatisticsVBoxRight.addWidget(self.accuracyLabel) outputHBox.addLayout(predictionStatisticsVBoxLeft) outputHBox.addLayout(predictionStatisticsVBoxRight) layout.addLayout(outputHBox) self.setLayout(layout) # mouse button press event press_event_id = self.canvas.mpl_connect('button_press_event', self.onclick) # motion_event_id = self.canvas.mpl_connect('motion_notify_event', self.on_move) self.plot() self.model = fNIRLib.load_model()
def __init__(self, data_analyzer: DataAnalyzer, parent=None): super().__init__(parent) self.setWindowTitle('Окно графиков') self.setMinimumSize(1200, 800) self.data_analyzer = data_analyzer self.chart_view = ChartView() self.chart_view.x_time_scaled = True self.chart_view.setMinimumSize(1000, 800) # ================ # Разметка виджета # ================ #Словарь для хранения лейблов со значениеями статистических характеристик self.param_label_container = {} #Список параметров для построения self.combo_headers = QComboBox() #Кнопка для построения Преобр. Фурье fft_plot_button = QPushButton() fft_plot_button.setText('Преобразование Фурье') fft_plot_button.clicked.connect(self.fft_build_plot_clicked) #Кнопка для вызова окна Нейронной сети neural_button = QPushButton() neural_button.setText('Окно обучения нейронной сети') neural_button.clicked.connect(self.neural_button_click) #layout - groupbox for measure info (station id, detector SN) measure_info_layout = QVBoxLayout() station_lb = QLabel('Номер станции: ' + str(data_analyzer.station)) sn_lb = QLabel('Серийный номер датчика: ' + data_analyzer.detector) measure_info_layout.addWidget(station_lb) measure_info_layout.addWidget(sn_lb) group_box_info = QGroupBox() group_box_info.setTitle('Основная информация об измерении') group_box_info.setLayout(measure_info_layout) #layout - group box for settings plot widgets plot_controls_layout = QVBoxLayout() plot_controls_layout.addWidget(self.combo_headers, 0, Qt.AlignTop) plot_controls_layout.addWidget(fft_plot_button, 0, Qt.AlignTop) plot_controls_layout.addWidget(neural_button, 0, Qt.AlignTop) group_box_plot = QGroupBox() group_box_plot.setLayout(plot_controls_layout) group_box_plot.setTitle('Параметры построения графика') #layout - labels with param name and value params_layout = QGridLayout() self.add_statistics_parm('Минимальное значение', params_layout) self.add_statistics_parm('Максимальное значение', params_layout) self.add_statistics_parm('Мат. ожидание', params_layout) self.add_statistics_parm('Дисперсия', params_layout) self.add_statistics_parm('Медиана', params_layout) self.add_statistics_parm('Мода', params_layout) self.add_statistics_parm('Размах', params_layout) #Статистические параметры group_box_param = QGroupBox() group_box_param.setTitle('Статистические характеристики') group_box_param.setLayout(params_layout) #layout - для всех настроек all_param_layout = QVBoxLayout() all_param_layout.addWidget(group_box_info) all_param_layout.addWidget(group_box_plot) all_param_layout.addWidget(group_box_param) #layout - Дочерний слой основного слоя layout = QGridLayout() layout.addWidget(self.chart_view, 0, 0) layout.addLayout(all_param_layout, 0, 1, Qt.AlignTop) #layout - Основной слой main_layout = QVBoxLayout() main_layout.addLayout(layout) self.setLayout(main_layout) #Сигнал о изменении текста comboBox с заголовками данных self.combo_headers.currentTextChanged.connect(self.buildplot) #Заполним comboBox for header in data_analyzer.get_headers(): self.combo_headers.addItem(header) # ============= # Создание меню # ============= menu_bar = QMenuBar() file_menu = menu_bar.addMenu('Файл') export_data_action = QAction('Экспортировать данные', self) export_data_action.triggered.connect(self.export_data) file_menu.addAction(export_data_action) main_layout.setMenuBar(menu_bar)
def initUI(self): #ReplaceModel ReplaceModel=QStandardItemModel() ReplaceModel.setColumnCount(3) ReplaceModel.setHorizontalHeaderLabels(["Найти","Заменить на","Настройки"]) #/ReplaceModel #replaceTable replaceTable = QTableView(self) #replaceTable.setToolTip("Таблица поиска и замены,\nдобавьте строку и заполните текст для поиска и замены,\nвы также можете выбрать индивидуальные опции поиска для данной строки") #replaceTable.horizontalHeader().setToolTip("Найти - Текст для поиска\nЗаменить - Текст замены\nЗн. - Подстановочные знаки\nЦв. - Выделение цветом\nЖ - Выделение жирным шрифтом\nН - Изменять надписи\nWA - Изменять объкты WordArt") replaceTable.setModel(ReplaceModel) replaceTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) replaceTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents) """replaceTable.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeToContents)""" replaceTable.horizontalHeader().resizeSection(0,500) replaceTable.setItemDelegateForColumn(0,PlainTextEditDelegate(replaceTable)) replaceTable.setItemDelegateForColumn(1,PlainTextEditDelegate(replaceTable)) #btnDeleg=ButtonDelegate(replaceTable) #btnDeleg.clicked.connect(self.setItemOpt) #replaceTable.clicked.connect(self.setItemOpt) #replaceTable.setItemDelegateForColumn(2,btnDeleg) #replaceTable.setItemDelegateForColumn(6,CheckBoxDelegate(replaceTable)) #/replaceTable #buttonBox sklonPadejBtn=QPushButton("Просклонять") addRowBtn=QPushButton("Добавить строку") delRowBtn=QPushButton("Удалить строку") clearTable=QPushButton("Очистить") buttonBox = QDialogButtonBox(Qt.Horizontal) buttonBox.addButton(sklonPadejBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(addRowBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(delRowBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(clearTable, QDialogButtonBox.ActionRole) #/buttonBox #mainLayout mainLayout = QVBoxLayout() mainLayout.setContentsMargins(0,0,0,0) self.optionWdgt=Options() mainLayout.setMenuBar(self.optionWdgt) mainLayout.addWidget(replaceTable) mainLayout.addWidget(buttonBox) #/mainLayout #self self.setLayout(mainLayout) self.ReplaceModel=ReplaceModel self.replaceTable=replaceTable #/self #connections sklonPadejBtn.clicked.connect(self.addSklonenie) addRowBtn.clicked.connect(self.addRow) delRowBtn.clicked.connect(self.delRow) clearTable.clicked.connect(self.clearReplaceTable) ReplaceModel.itemChanged.connect(self.ChangeReplaceList)
def createAllDataTab(self): # i = 0 because it is the first tab in all lists i = 0 self.tabsList.append(QWidget()) # a figure instance to plot on self.figures.append(plt.figure()) # this is the Canvas Widget that displays the plot or (figure) self.canvases.append(FigureCanvas(self.figures[i])) # this is the Navigation Toolbar for the top of the plot self.toolbars.append(NavigationToolbar(self.canvases[i], self)) # create the layout and menu layout = QVBoxLayout() layout.setMenuBar(self.menu_bar) layout.addWidget(self.toolbars[i]) layout.addWidget(self.canvases[i]) outputHBox = QHBoxLayout() # create the labels that we will need to access again self.brainStateLabels.append(QLabel("Brain State : ")) self.brainStateLabels[i].setFixedSize(200, 20) self.pointClickedLabels.append(QLabel("")) self.pointClickedLabels[i].setFixedSize(400, 20) # predict on all Button predictButton = QPushButton("Predict on All Data", self) predictButton.setToolTip('Predicts on all data [0, (Time = Max)]') # connect the event to the button when clicked predictButton.clicked.connect(self.predictOnAll) predictButton.setFixedSize(200, 25) self.predictAllButtons.append(predictButton) # add all widgets to the layouts, 3 VBox's for 3 Columns predictionStatisticsVBoxLeft = QVBoxLayout() predictionStatisticsVBoxLeft.addWidget(self.brainStateLabels[i]) predictionStatisticsVBoxMiddle = QVBoxLayout() predictionStatisticsVBoxMiddle.addWidget(self.pointClickedLabels[i]) predictionStatisticsVBoxRight = QVBoxLayout() predictionStatisticsVBoxRight.addWidget(self.predictAllButtons[i]) # add them all to the bottom HBox (row) outputHBox.addLayout(predictionStatisticsVBoxLeft) outputHBox.addLayout(predictionStatisticsVBoxMiddle) outputHBox.addLayout(predictionStatisticsVBoxRight) # set the layout layout.addLayout(outputHBox) self.tabsList[i].setLayout(layout) # add the new tab to the widget self.tab_widget.addTab(self.tabsList[i], "All Tasks Data") # motion_event_id = self.canvas.mpl_connect('motion_notify_event', self.on_move) #TODO IF A ON_MOUSE_MOVE EVENT IS NEEDED # press_event_id = self.canvases[i].mpl_connect('button_press_event', lambda event: self.onclick(event, i)) # plot the data on the i'th tab self.plotAllData() self.tabsList[i].setLayout(layout)
def ui(self): self.fname = None screen_res = ImageGrab.grab().size self.lbl = QLabel(self) self.lbl.setAlignment(Qt.AlignCenter) self.pixmap = QPixmap(self.fname) self.lbl.setPixmap(self.pixmap) self.lbl.setMinimumSize(screen_res[0] // 10, screen_res[1] // 10) self.lbl.installEventFilter(self) hbox = QVBoxLayout(self) hbox.addWidget(self.lbl) self.setLayout(hbox) self.setGeometry(screen_res[0] // 5, screen_res[1] // 5, screen_res[0] // 2, screen_res[1] // 2) self.setWindowState(Qt.WindowMaximized) self.setWindowTitle('PhotoFilter') self.setWindowIcon(QIcon(self.resource_path('data\Logo.ico'))) openFile = QAction('Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open file') openFile.triggered.connect(self.open_file) saveFile = QAction('Save As...', self) saveFile.setShortcut('Ctrl+S') saveFile.setStatusTip('Save file as...') saveFile.triggered.connect(self.save_file) orig = QAction('Original', self) orig.setShortcut('ctrl+I') orig.setStatusTip('Original image') orig.triggered.connect(self.original_image) blur = QAction('Blur', self) blur.setShortcut('ctrl+L') blur.setStatusTip('Blur filter') blur.triggered.connect(self.blur_filter) grayscale = QAction('Grayscale', self) grayscale.setShortcut('ctrl+G') grayscale.setStatusTip('Grayscale filter') grayscale.triggered.connect(self.grayscale_filter) stereo = QAction('Stereo', self) stereo.setShortcut('Ctrl+T') stereo.setStatusTip('Stereo filter') stereo.triggered.connect(self.stereo_filter) negativ = QAction('Negativ', self) negativ.setShortcut('ctrl+N') negativ.setStatusTip('Negativ filter') negativ.triggered.connect(self.negativ_filter) bw = QAction('Black-white', self) bw.setShortcut('ctrl+B') bw.setStatusTip('Black-white filter') bw.triggered.connect(self.black_white_filter) contour = QAction('Contour', self) contour.setShortcut('ctrl+U') contour.setStatusTip('Contour filter') contour.triggered.connect(self.contour_filter) texture = QAction('Texture', self) texture.setShortcut('ctrl+E') texture.setStatusTip('Texture filter') texture.triggered.connect(self.texture_filter) menubar = QMenuBar() fileMenu = menubar.addMenu('&File') filterMenu = menubar.addMenu('&Filters') fileMenu.addAction(openFile) fileMenu.addAction(saveFile) filterMenu.addAction(orig) filterMenu.addAction(blur) filterMenu.addAction(grayscale) filterMenu.addAction(stereo) filterMenu.addAction(negativ) filterMenu.addAction(bw) filterMenu.addAction(contour) filterMenu.addAction(texture) hbox.setMenuBar(menubar)
def initUI(self): #ReplaceModel ReplaceModel = QStandardItemModel() ReplaceModel.setColumnCount(3) ReplaceModel.setHorizontalHeaderLabels( ["Найти", "Заменить на", "Настройки"]) #/ReplaceModel #replaceTable replaceTable = QTableView(self) #replaceTable.setToolTip("Таблица поиска и замены,\nдобавьте строку и заполните текст для поиска и замены,\nвы также можете выбрать индивидуальные опции поиска для данной строки") #replaceTable.horizontalHeader().setToolTip("Найти - Текст для поиска\nЗаменить - Текст замены\nЗн. - Подстановочные знаки\nЦв. - Выделение цветом\nЖ - Выделение жирным шрифтом\nН - Изменять надписи\nWA - Изменять объкты WordArt") replaceTable.setModel(ReplaceModel) replaceTable.horizontalHeader().setSectionResizeMode( 1, QHeaderView.Stretch) replaceTable.horizontalHeader().setSectionResizeMode( 2, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode( 3, QHeaderView.ResizeToContents) """replaceTable.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents) replaceTable.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeToContents)""" replaceTable.horizontalHeader().resizeSection(0, 500) replaceTable.setItemDelegateForColumn( 0, PlainTextEditDelegate(replaceTable)) replaceTable.setItemDelegateForColumn( 1, PlainTextEditDelegate(replaceTable)) #btnDeleg=ButtonDelegate(replaceTable) #btnDeleg.clicked.connect(self.setItemOpt) #replaceTable.clicked.connect(self.setItemOpt) #replaceTable.setItemDelegateForColumn(2,btnDeleg) #replaceTable.setItemDelegateForColumn(6,CheckBoxDelegate(replaceTable)) #/replaceTable #buttonBox sklonPadejBtn = QPushButton("Просклонять") addRowBtn = QPushButton("Добавить строку") delRowBtn = QPushButton("Удалить строку") clearTable = QPushButton("Очистить") buttonBox = QDialogButtonBox(Qt.Horizontal) buttonBox.addButton(sklonPadejBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(addRowBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(delRowBtn, QDialogButtonBox.ActionRole) buttonBox.addButton(clearTable, QDialogButtonBox.ActionRole) #/buttonBox #mainLayout mainLayout = QVBoxLayout() mainLayout.setContentsMargins(0, 0, 0, 0) self.optionWdgt = Options() mainLayout.setMenuBar(self.optionWdgt) mainLayout.addWidget(replaceTable) mainLayout.addWidget(buttonBox) #/mainLayout #self self.setLayout(mainLayout) self.ReplaceModel = ReplaceModel self.replaceTable = replaceTable #/self #connections sklonPadejBtn.clicked.connect(self.addSklonenie) addRowBtn.clicked.connect(self.addRow) delRowBtn.clicked.connect(self.delRow) clearTable.clicked.connect(self.clearReplaceTable) ReplaceModel.itemChanged.connect(self.ChangeReplaceList)
def _build_ui(self): layout = QVBoxLayout() self.file_selector = FilereaderComboBox(self.session) self.file_selector.currentIndexChanged.connect(self.fill_table) layout.insertWidget(0, self.file_selector, 0) self.table = QTableWidget() self.table.setColumnCount(2) self.table.setHorizontalHeaderLabels(['Data', 'Value']) self.table.horizontalHeader().setStretchLastSection(False) self.table.horizontalHeader().setSectionResizeMode( 0, QHeaderView.Interactive) self.table.setEditTriggers(QTableWidget.NoEditTriggers) self.table.horizontalHeader().setSectionResizeMode( 1, QHeaderView.Stretch) self.table.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) layout.insertWidget(1, self.table, 1) self.filter = QLineEdit() self.filter.setPlaceholderText("filter data") self.filter.textChanged.connect(self.apply_filter) self.filter.setClearButtonEnabled(True) layout.insertWidget(2, self.filter, 0) menu = QMenuBar() export = menu.addMenu("&Export") copy = QAction("&Copy CSV to clipboard", self.tool_window.ui_area) copy.triggered.connect(self.copy_csv) shortcut = QKeySequence(Qt.CTRL + Qt.Key_C) copy.setShortcut(shortcut) export.addAction(copy) self.copy = copy save = QAction("&Save CSV...", self.tool_window.ui_area) save.triggered.connect(self.save_csv) #this shortcut interferes with main window's save shortcut #I've tried different shortcut contexts to no avail #thanks Qt... #shortcut = QKeySequence(Qt.CTRL + Qt.Key_S) #save.setShortcut(shortcut) #save.setShortcutContext(Qt.WidgetShortcut) export.addAction(save) delimiter = export.addMenu("Delimiter") # comma = QAction("comma", self.tool_window.ui_area, checkable=True) # comma.setChecked(self.settings.delimiter == "comma") # comma.triggered.connect(lambda *args, delim="comma": self.settings.__setattr__("delimiter", delim)) # delimiter.addAction(comma) tab = QAction("tab", self.tool_window.ui_area, checkable=True) tab.setChecked(self.settings.delimiter == "tab") tab.triggered.connect(lambda *args, delim="tab": self.settings. __setattr__("delimiter", delim)) delimiter.addAction(tab) # space = QAction("space", self.tool_window.ui_area, checkable=True) # space.setChecked(self.settings.delimiter == "space") # space.triggered.connect(lambda *args, delim="space": self.settings.__setattr__("delimiter", delim)) # delimiter.addAction(space) semicolon = QAction("semicolon", self.tool_window.ui_area, checkable=True) semicolon.setChecked(self.settings.delimiter == "semicolon") semicolon.triggered.connect(lambda *args, delim="semicolon": self. settings.__setattr__("delimiter", delim)) delimiter.addAction(semicolon) add_header = QAction("&Include CSV header", self.tool_window.ui_area, checkable=True) add_header.setChecked(self.settings.include_header) add_header.triggered.connect(self.header_check) export.addAction(add_header) tab.triggered.connect( lambda *args, action=semicolon: action.setChecked(False)) semicolon.triggered.connect( lambda *args, action=tab: action.setChecked(False)) archive = QAction("Include archive if present", self.tool_window.ui_area, checkable=True) archive.triggered.connect( lambda checked: setattr(self.settings, "archive", checked)) archive.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) archive.setChecked(self.settings.archive) export.addAction(archive) unit = menu.addMenu("&Units") energy = unit.addMenu("energy") hartree = QAction("Hartree", self.tool_window.ui_area, checkable=True) hartree.setChecked(self.settings.energy == "Hartree") kcal = QAction("kcal/mol", self.tool_window.ui_area, checkable=True) kcal.setChecked(self.settings.energy == "kcal/mol") kjoule = QAction("kJ/mol", self.tool_window.ui_area, checkable=True) kjoule.setChecked(self.settings.energy == "kJ/mol") energy.addAction(hartree) energy.addAction(kcal) energy.addAction(kjoule) hartree.triggered.connect( lambda *args, val="Hartree": setattr(self.settings, "energy", val)) hartree.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) hartree.triggered.connect( lambda *args, action=kcal: action.setChecked(False)) hartree.triggered.connect( lambda *args, action=kjoule: action.setChecked(False)) kcal.triggered.connect(lambda *args, val="kcal/mol": setattr( self.settings, "energy", val)) kcal.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) kcal.triggered.connect( lambda *args, action=hartree: action.setChecked(False)) kcal.triggered.connect( lambda *args, action=kjoule: action.setChecked(False)) kjoule.triggered.connect( lambda *args, val="kJ/mol": setattr(self.settings, "energy", val)) kjoule.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) kjoule.triggered.connect( lambda *args, action=hartree: action.setChecked(False)) kjoule.triggered.connect( lambda *args, action=kcal: action.setChecked(False)) mass = unit.addMenu("mass") kg = QAction("kg", self.tool_window.ui_area, checkable=True) kg.setChecked(self.settings.mass == "kg") amu = QAction("Da", self.tool_window.ui_area, checkable=True) amu.setChecked(self.settings.mass == "Da") mass.addAction(kg) mass.addAction(amu) kg.triggered.connect( lambda *args, val="kg": setattr(self.settings, "mass", val)) kg.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) kg.triggered.connect( lambda *args, action=amu: action.setChecked(False)) amu.triggered.connect( lambda *args, val="Da": setattr(self.settings, "mass", val)) amu.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) amu.triggered.connect( lambda *args, action=kg: action.setChecked(False)) rot_const = unit.addMenu("rotational constants") temperature = QAction("K", self.tool_window.ui_area, checkable=True) temperature.setChecked(self.settings.rot_const == "K") hertz = QAction("GHz", self.tool_window.ui_area, checkable=True) hertz.setChecked(self.settings.rot_const == "GHz") rot_const.addAction(temperature) rot_const.addAction(hertz) temperature.triggered.connect( lambda *args, val="K": setattr(self.settings, "rot_const", val)) temperature.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) temperature.triggered.connect( lambda *args, action=hertz: action.setChecked(False)) hertz.triggered.connect( lambda *args, val="GHz": setattr(self.settings, "rot_const", val)) hertz.triggered.connect( lambda *args: self.fill_table(self.file_selector.count() - 1)) hertz.triggered.connect( lambda *args, action=temperature: action.setChecked(False)) menu.setNativeMenuBar(False) self._menu = menu layout.setMenuBar(menu) if len(self.session.filereader_manager.list()) > 0: self.fill_table(0) self.tool_window.ui_area.setLayout(layout) self.tool_window.manage(None)
class Dialog(QDialog): def __init__(self): super(Dialog, self).__init__() self.NumGridRows = 3 self.NumButtons = 4 self.menuBar = self.createMenu() self.horizontalGroupBox = self.createHorizontalGroupBox() self.gridGroupBox = self.createGridGroupBox() self.formGroupBox = self.createFormGroupBox() self.bigEditor = QTextEdit() self.bigEditor.setPlainText(self.tr("This widget takes up all the " "remaining space in the top-level layout.")) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.mainLayout = QVBoxLayout() self.mainLayout.setMenuBar(self.menuBar) self.mainLayout.addWidget(self.horizontalGroupBox) self.mainLayout.addWidget(self.gridGroupBox) self.mainLayout.addWidget(self.formGroupBox) self.mainLayout.addWidget(self.bigEditor) self.mainLayout.addWidget(self.buttonBox) self.setLayout(self.mainLayout) self.setWindowTitle(self.tr("Basic Layouts")) def createMenu(self): menuBar = QMenuBar() fileMenu = QMenu(self.tr("&File"), self) exitAction = fileMenu.addAction(self.tr("E&xit")) menuBar.addMenu(fileMenu) exitAction.triggered.connect(self.accept) return menuBar def createHorizontalGroupBox(self): horizontalGroupBox = QGroupBox(self.tr("Horizontal layout")) layout = QHBoxLayout() for i in range(self.NumButtons): button = QPushButton(self.tr("Button " + str(i + 1))) layout.addWidget(button) horizontalGroupBox.setLayout(layout) return horizontalGroupBox def createGridGroupBox(self): gridGroupBox = QGroupBox(self.tr("Grid layout")) layout = QGridLayout() label1 = QLabel(self.tr("Line 1")) label2 = QLabel(self.tr("Line 2")) label3 = QLabel(self.tr("Line 3")) lineEdit1 = QLineEdit() lineEdit2 = QLineEdit() lineEdit3 = QLineEdit() layout.addWidget(label1, 0, 0) layout.addWidget(lineEdit1, 0, 1) layout.addWidget(label2, 2, 0) layout.addWidget(lineEdit2, 2, 1) layout.addWidget(label3, 3, 0) layout.addWidget(lineEdit3, 3, 1) # for i in range(self.NumGridRows): # label = QLabel(self.tr("Line " + str(i + 1))) # lineEdit = QLineEdit() # layout.addWidget(label, i + 1, 0) # layout.addWidget(lineEdit, i + 1, 1) smallEditor = QTextEdit() puk = smallEditor.sizeHint() smallEditor.setPlainText(self.tr("This widget takes up about two " "thirds of the grid layout.")) layout.addWidget(smallEditor, 0, 2, 4, 1) layout.setColumnStretch(1, 10) layout.setColumnStretch(2, 20) gridGroupBox.setLayout(layout) return gridGroupBox def createFormGroupBox(self): formGroupBox = QGroupBox(self.tr("Form layout")) layout = QFormLayout() layout.addRow(QLabel(self.tr("Line 1:")), QLineEdit()) layout.addRow(QLabel(self.tr("Line 2, long text:")), QComboBox()) layout.addRow(QLabel(self.tr("Line 3:")), QSpinBox()) formGroupBox.setLayout(layout) return formGroupBox
class Ui_SmainWindow(object): def setupUi(self, SmainWindow): width = QDesktopWidget().screenGeometry().width() height = QDesktopWidget().screenGeometry().height() '''screen_resolution = app.desktop().screenGeometry() width, height = screen_resolution.width(), screen_resolution.height()''' SmainWindow.setObjectName("SmainWindow") SmainWindow.resize((3400/3840)*width,(1700/2160)*height) SmainWindow.setMaximumSize(QtCore.QSize((3400/3840)*width,(1700/2160)*height)) SmainWindow.setMinimumSize(QtCore.QSize((3400/3840)*width,(1700/2160)*height)) self.centralwidget = QtWidgets.QWidget(SmainWindow) self.centralwidget.setObjectName("centralwidget") self.line = QtWidgets.QFrame(self.centralwidget) self.line.setGeometry(QtCore.QRect((20/3840)*width, (1070/2160)*height ,(3300/3840)*width, (30/2160)*height)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setLineWidth(5) self.line.setObjectName("line") self.line2 = QtWidgets.QFrame(self.centralwidget) self.line2.setGeometry(QtCore.QRect((1440/3840)*width, (290/2160)*height ,(30/3840)*width, (700/2160)*height)) self.line2.setFrameShape(QtWidgets.QFrame.VLine) self.line2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line2.setLineWidth(5) self.line2.setObjectName("line2") self.line3 = QtWidgets.QFrame(self.centralwidget) self.line3.setGeometry(QtCore.QRect((2290/3840)*width, (290/2160)*height ,(30/3840)*width, (700/2160)*height)) self.line3.setFrameShape(QtWidgets.QFrame.VLine) self.line3.setFrameShadow(QtWidgets.QFrame.Sunken) self.line3.setLineWidth(5) self.line3.setObjectName("line3") self.layout = QVBoxLayout(self.centralwidget) self.fig = Figure(figsize=((8/3840)*width, (6.5/2160)*height )) self.canvas = FigureCanvas(self.fig) self.layout.addWidget(self.canvas) self.widget = QWidget(self.centralwidget) #self.toolbar = NavigationToolbar(self.canvas, self.widget) self.layout.setMenuBar(NavigationToolbar(self.canvas,self.widget)) self.widget.setLayout(self.layout) self.widget.setGeometry((1480/3840)*width,(290/2160)*height,(800/3840)*width,(600/2160)*height) #layout.addWidget(self.canvas) ''' self.graphicsView = PlotWidget(self.centralwidget) self.graphicsView.setGeometry(QtCore.QRect(700, 150, 700, 700)) self.graphicsView.setObjectName("graphicsView") ''' self.chartView = QChartView(self.centralwidget) self.chartView.setGeometry(QtCore.QRect((200/3840)*width, (1090/2160)*height, (1700/3840)*width, (500/2160)*height)) self.chartView.setObjectName("graphicsView") self.browseFile = QtWidgets.QPushButton(self.centralwidget) self.browseFile.setGeometry(QtCore.QRect((200/3840)*width, (50/2160)*height, (350/3840)*width, (50/2160)*height)) self.browseFile.setObjectName("browseFile") self.filenameLabel = QtWidgets.QLabel(self.centralwidget) self.filenameLabel.setGeometry(QtCore.QRect((700/3840)*width, (55/2160)*height, (350/3840)*width, (70/2160)*height)) self.filenameLabel.setObjectName("filenameLabel") self.datasize = QtWidgets.QLabel(self.centralwidget) self.datasize.setGeometry(QtCore.QRect((20/3840)*width, (105/2160)*height, (350/3840)*width, (70/2160)*height)) self.datasize.setObjectName("datasize") self.datasize.setText("Data Shape :") self.datasize.setStyleSheet( """QLabel { font: bold; font-size: 10pt; font-family: Typograf;}""") self.datashape = QtWidgets.QLabel(self.centralwidget) self.datashape.setGeometry(QtCore.QRect((250/3840)*width, (105/2160)*height, (350/3840)*width, (70/2160)*height)) self.datashape.setObjectName("datashape") self.datashape.setStyleSheet( """QLabel { font: bold; font-size: 12pt; font-family: Typograf;}""") self.atributelabe = QtWidgets.QLabel(self.centralwidget) self.atributelabe.setGeometry(QtCore.QRect((295/3840)*width, (200/2160)*height, (350/3840)*width, (70/2160)*height)) self.atributelabe.setObjectName("atributelabe") self.atributelabe.setText("Variables") self.atributelabe.setStyleSheet( """QLabel { font: bold; font-size: 10pt; font-family: Typograf;}""") self.statisticlabel = QtWidgets.QLabel(self.centralwidget) self.statisticlabel.setGeometry(QtCore.QRect((1020/3840)*width, (200/2160)*height, (350/3840)*width, (70/2160)*height)) self.statisticlabel.setObjectName("statisticlabel") self.statisticlabel.setText("Statistics") self.statisticlabel.setStyleSheet( """QLabel { font: bold; font-size: 10pt; font-family: Typograf;}""") self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.textBrowser.setGeometry(QtCore.QRect((740/3840)*width, (290/2160)*height, (700/3840)*width, (700/2160)*height)) self.textBrowser.setObjectName("textBrowser") self.textBrowser.setStyleSheet( """QTextBrowser { font: bold; font-size: 12pt; font-family: Courier;}""") self.missingvalulabel = QtWidgets.QLabel(self.centralwidget) self.missingvalulabel.setGeometry(QtCore.QRect((2330/3840)*width, (500/2160)*height, (250/3840)*width, (100/2160)*height)) self.missingvalulabel.setObjectName("missingvalulabel") self.missingvalulabel.setText("Show Missing \nValues") self.missingvalulabel.setStyleSheet( """QLabel { font: bold; font-size: 10pt; font-family: Courier;}""") self.resetbtn = QtWidgets.QPushButton(self.centralwidget) self.resetbtn.setGeometry(QtCore.QRect((2330/3840)*width, (300/2160)*height, (250/3840)*width, (50/2160)*height)) self.resetbtn.setObjectName("resetbtn") self.resetbtn.setText("Reset") self.resetbtn.setEnabled(False) self.perclm = QtWidgets.QPushButton(self.centralwidget) self.perclm.setGeometry(QtCore.QRect((2330/3840)*width, (600/2160)*height, (250/3840)*width, (50/2160)*height)) self.perclm.setObjectName("perclm") self.perclm.setText("PerColumn") self.perclm.setEnabled(False) self.perrow = QtWidgets.QPushButton(self.centralwidget) self.perrow.setGeometry(QtCore.QRect((2330/3840)*width, (670/2160)*height, (250/3840)*width, (50/2160)*height)) self.perrow.setObjectName("perrow") self.perrow.setText("PerRow") self.perrow.setEnabled(False) self.datainfo = QtWidgets.QLabel(self.centralwidget) self.datainfo.setGeometry(QtCore.QRect((2850/3840)*width, (200/2160)*height, (350/3840)*width, (70/2160)*height)) self.datainfo.setObjectName("statisticlabel") self.datainfo.setText("Data Info") self.datainfo.setStyleSheet( """QLabel { font: bold; font-size: 10pt; font-family: Typograf;}""") self.infor = QtWidgets.QTextBrowser(self.centralwidget) self.infor.setGeometry(QtCore.QRect((2600/3840)*width, (290/2160)*height, (700/3840)*width, (700/2160)*height)) self.infor.setObjectName("infor") self.infor.setStyleSheet( """QTextBrowser { font: bold; font-family: Courier;}""") self.calstatistics = QtWidgets.QPushButton(self.centralwidget) self.calstatistics.setGeometry(QtCore.QRect((200/3840)*width, (1020/2160)*height, (350/3840)*width, (50/2160)*height)) self.calstatistics.setObjectName("calstatistics") self.listWidget = QtWidgets.QListWidget(self.centralwidget) self.listWidget.setGeometry(QtCore.QRect((20/3840)*width, (290/2160)*height, (700/3840)*width, (700/2160)*height)) self.listWidget.setObjectName("listWidget") self.listWidget.setAlternatingRowColors(True) self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.comboBox.setGeometry(QtCore.QRect((1480/3840)*width,(120/2160)*height,(800/3840)*width,(50/2160)*height)) self.comboBox.setObjectName("comboBox") self.comboBox2 = QtWidgets.QComboBox(self.centralwidget) self.comboBox2.setGeometry(QtCore.QRect((1480/3840)*width,(200/2160)*height,(800/3840)*width,(50/2160)*height)) self.comboBox2.setObjectName("comboBox2") self.report = QtWidgets.QPushButton(self.centralwidget) self.report.setGeometry(QtCore.QRect((1700/3840)*width, (1020/2160)*height, (300/3840)*width, (50/2160)*height)) self.report.setObjectName("report") self.report.setText("Generate Report") self.back = QtWidgets.QPushButton(self.centralwidget) self.back.setGeometry(QtCore.QRect((5/3840)*width, (1600/2160)*height, (300/3840)*width, (50/2160)*height)) self.back.setObjectName("back") self.back.setText("Back") self.back.setStyleSheet( """QPushButton { border-radius:0; border:0; text-align:left; padding-left:70px; qproperty-icon:url('back.png'); qproperty-iconSize: 40px 40px;}""") SmainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(SmainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, (469/3840)*width, (22/2160)*height)) self.menubar.setObjectName("menubar") SmainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(SmainWindow) self.statusbar.setObjectName("statusbar") SmainWindow.setStatusBar(self.statusbar) self.retranslateUi(SmainWindow) QtCore.QMetaObject.connectSlotsByName(SmainWindow) def retranslateUi(self, SmainWindow): _translate = QtCore.QCoreApplication.translate SmainWindow.setWindowTitle(_translate("SmainWindow", "Data Statistical Analysis")) self.browseFile.setText(_translate("SmainWindow", "Open File")) self.browseFile.clicked.connect(self.pushButton_handler) self.filenameLabel.setText(_translate("SmainWindow", "")) self.calstatistics.setText(_translate("SmainWindow", "Calculate Statistics")) self.calstatistics.clicked.connect(self.cal) self.listWidget.clicked.connect(self.listview_clicked) self.resetbtn.clicked.connect(self.information) self.perclm.clicked.connect(self.num_missing) self.perrow.clicked.connect(self.row_missing) self.report.clicked.connect(self.generatereport) def pushButton_handler(self): self.open_dialog_box() def open_dialog_box(self): filename = QFileDialog.getOpenFileName(None, 'Open File', r"~/Desktop", '*.csv') path = filename[0] with open(path, "r") as fpath: self.infor.clear() self.comboBox.clear() self.comboBox2.clear() self.datasetheaders=[] self.filenameLabel.setText(str(path)) self.filenameLabel.adjustSize() pandas.set_option('display.max_rows', None) self.dataset=pandas.read_csv(fpath) buf = io.StringIO() self.dataset.info(verbose=True, null_counts=True,buf=buf) s = buf.getvalue() self.perclm.setDisabled(False) self.perrow.setDisabled(False) self.infor.append(s) SIZE=self.dataset.shape self.datashape.setText(str(SIZE)) self.create_piechart() #headers=self.dataset.columns self.datasetheaders=self.dataset.columns.to_numpy() self.listWidget.clear() for i in range(len(self.datasetheaders)-1): self.listWidget.insertItem(i,self.datasetheaders[i]) for i in range(len(self.datasetheaders)-1): self.comboBox.addItem(self.datasetheaders[i]) for i in range(len(self.datasetheaders)-1): self.comboBox2.addItem(self.datasetheaders[i]) self.setup() self.comboBox.currentIndexChanged.connect(self.setup) self.comboBox2.currentIndexChanged.connect(self.setup) #print(unique_headers) '''print ("Missing values per column:") print(self.dataset.apply(lambda x: sum(x.isnull()))) ''' def generatereport(self): try: profile = ProfileReport(self.dataset) profile.to_file(output_file="AnalysisReport.html") print("yes") except Exception as e: print(repr(e)) def information(self): self.infor.clear() self.resetbtn.setEnabled(False) self.perrow.setDisabled(False) self.perclm.setDisabled(False) buf = io.StringIO() self.dataset.info(verbose=True, null_counts=True,buf=buf) s = buf.getvalue() self.infor.append(s) def row_missing(self): self.perrow.setEnabled(False) self.perclm.setDisabled(False) self.resetbtn.setDisabled(False) self.infor.clear() #self.infor.append(str(self.dataset.apply(lambda x: sum(x.isnull())))) self.infor.append(str(self.dataset.apply(self.missing, axis=1))) def num_missing(self): self.perclm.setEnabled(False) self.perrow.setDisabled(False) self.resetbtn.setDisabled(False) self.infor.clear() #self.infor.append(str(self.dataset.apply(lambda x: sum(x.isnull())))) self.infor.append(str(self.dataset.apply(self.missing, axis=0))) def missing(self,x): return sum(x.isnull()) def setup(self): try: print("fig") iris=self.dataset x_index = 0 y_index = 1 w=iris.iloc[:,self.comboBox.currentIndex()] z=iris.iloc[:,self.comboBox2.currentIndex()] y=iris.iloc[:,-1].values # this formatter will label the colorbar with the correct target names #formatter = plt.FuncFormatter(y) #plt.figure(figsize=(5, 4)) ax = self.fig.add_subplot(111) ax.clear() scatter=ax.scatter(w, z, c=y) #self.figure.colorbar(ticks=y) #ax.xlabel("iris.feature_names[x_index]") #ax.ylabel("iris.feature_names[y_index]") ax.set_xlabel(self.comboBox.currentText(), fontsize=25) ax.set_ylabel(self.comboBox2.currentText(), fontsize=25) ax.set_title('Scatter Plot',fontsize=25) legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(legend1) self.widget.adjustSize() print("fig123456789") except Exception as e: print(repr(e)) def cal(self): #self.graphicsView.clear() z=self.dataset w=z.iloc[:,self.a] self.textBrowser.setText("Mean:\n"+str(np.mean(w))+"\nMedian:\n"+str(np.median(w))+"\nMode:\n"+str(stats.mode(w))+"\nvariance:\n"+str(np.var(w))+"\nStdev:\n"+str(np.std(w))) #self.textBrowser.adjustSize() ''' pen = pg.mkPen(color=(255, 0, 0),width=8) self.graphicsView.setBackground('w') self.graphicsView.plot(w,symbol='+',symbolSize=30, pen=pen) ''' def listview_clicked(self): item=self.listWidget.currentRow() self.a=item def create_piechart(self): z=self.dataset w=z.iloc[:,-1] r=w.value_counts() p=r.to_numpy() y=w.nunique() df_val_counts = pandas.DataFrame(r) df_val_counts = df_val_counts.reset_index() df_val_counts.columns = ['unique_values', 'counts'] w=df_val_counts.iloc[:,0].to_numpy() k=df_val_counts.iloc[:,1].to_numpy() res = w.astype(str) series = QPieSeries() for i in range(y): series.append(res[i], k[i]) chart = self.chartView.chart() chart.removeAllSeries() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.AllAnimations) chart.setTitle("Pie Chart") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) #self.chartView = QChartView(chart) self.chartView.setRenderHint(QPainter.Antialiasing)
def createTab(self, i): ''' Generates the tab for the task at the index given :param i: task number ''' self.tabsList.append(QWidget()) # a figure instance to plot on self.figures.append(plt.figure()) # this is the Canvas Widget that displays the plot or (figure) self.canvases.append(FigureCanvas(self.figures[i])) # this is the Navigation Toolbar for the top of the plot self.toolbars.append(NavigationToolbar(self.canvases[i], self)) # create the layout and menu layout = QVBoxLayout() layout.setMenuBar(self.menu_bar) layout.addWidget(self.toolbars[i]) layout.addWidget(self.canvases[i]) outputHBox = QHBoxLayout() # create the labels that we will need to access again self.brainStateLabels.append(QLabel("Brain State : ")) self.brainStateLabels[i].setFixedSize(200, 20) self.pointClickedLabels.append(QLabel("")) self.pointClickedLabels[i].setFixedSize(400, 20) predictButton = QPushButton("Predict on Task Data", self) predictButton.setToolTip('Predicts on all task data') predictButton.clicked.connect(self.predictOnAll) predictButton.setFixedSize(200, 25) self.predictAllButtons.append(predictButton) predictionStatisticsVBoxLeft = QVBoxLayout() predictionStatisticsVBoxLeft.addWidget(self.brainStateLabels[i]) predictionStatisticsVBoxMiddle = QVBoxLayout() predictionStatisticsVBoxMiddle.addWidget(self.pointClickedLabels[i]) predictionStatisticsVBoxRight = QVBoxLayout() predictionStatisticsVBoxRight.addWidget(self.predictAllButtons[i]) outputHBox.addLayout(predictionStatisticsVBoxLeft) outputHBox.addLayout(predictionStatisticsVBoxMiddle) outputHBox.addLayout(predictionStatisticsVBoxRight) layout.addLayout(outputHBox) self.tabsList[i].setLayout(layout) # add the new tab to the widget self.tab_widget.addTab(self.tabsList[i], "Task " + str(i)) # plot the data on the i'th tab self.plot(i) self.tabsList[i].setLayout(layout)
def __init__(self, url, disable_browser): # initialize super().__init__() self._view = None self._is_closing = False # initialize the main window self.setWindowTitle(APP_NAME) if IS_FROZEN: base_dir = os.path.join(sys._MEIPASS, "vasl_templates/webapp") #pylint: disable=no-member,protected-access else: base_dir = os.path.join(os.path.split(__file__)[0], "webapp") self.setWindowIcon( QIcon(os.path.join(base_dir, "static/images/app.ico"))) # create the menu menu_bar = QMenuBar(self) file_menu = menu_bar.addMenu("&File") def add_action(caption, icon, handler): """Add a menu action.""" icon = QIcon( os.path.join(base_dir, "static/images/menu", icon ) if icon else None) action = QAction(icon, caption, self) action.triggered.connect(handler) file_menu.addAction(action) add_action("&Settings", "settings.png", self.on_settings) add_action("&About", "info.png", self.on_about) file_menu.addSeparator() add_action("E&xit", "exit.png", self.on_exit) # set the window geometry if disable_browser: self.setFixedSize(300, 108) else: # restore it from the previous session val = app_settings.value("MainWindow/geometry") if val: self.restoreGeometry(val) else: self.resize(1000, 650) self.setMinimumSize(1000, 620) # initialize the layout layout = QVBoxLayout(self) layout.setMenuBar(menu_bar) # FUDGE! We offer the option to disable the QWebEngineView since getting it to run # under Windows (especially older versions) is unreliable (since it uses OpenGL). # By disabling it, the program will at least start (in particular, the webapp server), # and non-technical users can then open an external browser and connect to the webapp # that way. Sigh... if not disable_browser: # initialize the web view self._view = QWebEngineView() layout.addWidget(self._view) # initialize the web page # nb: we create an off-the-record profile to stop the view from using cached JS files :-/ profile = QWebEngineProfile(None, self._view) version = APP_NAME.lower().replace(" ", "-") + "/" + APP_VERSION[1:] profile.setHttpUserAgent( re.sub(r"QtWebEngine/\S+", version, profile.httpUserAgent())) page = AppWebPage(profile, self._view) self._view.setPage(page) # create a web channel to communicate with the front-end web_channel = QWebChannel(page) # FUDGE! We would like to register a WebChannelHandler instance as the handler, but this crashes PyQt :-/ # Instead, we register ourself as the handler, and delegate processing to a WebChannelHandler. # The downside is that PyQt emits lots of warnings about our member variables not being properties, # but we filter them out in qtMessageHandler() :-/ self._web_channel_handler = WebChannelHandler(self) web_channel.registerObject("handler", self) page.setWebChannel(web_channel) # load the webapp url += "?pyqt=1" self._view.load(QUrl(url)) else: # show a minimal UI label = QLabel() label.setTextFormat(Qt.RichText) label.setText( "Running the <em>{}</em> application. <br>" \ "Click <a href='{}'>here</a> to connect." \ "<p> Close this window when you're done.".format( APP_NAME, url ) ) label.setStyleSheet( "QLabel { background-color: white ; padding: 0.5em ; }") label.setOpenExternalLinks(True) layout.addWidget(label) layout.setContentsMargins(QMargins(0, 0, 0, 0)) # register the instance assert MainWindow.instance is None MainWindow.instance = self