def __init__(self, parent=None): super(TreeContainer, self).__init__(parent) self._soln = None self.tree_loaded.connect(self._handleTreeLoaded) self._stacksize_compound = StackSizeCompound() self.combobox_compound = BoardComboCompound() self.dofp_compound = DoFPCompound() self.treeview_game = GameTreeView(self.combobox_compound.combobox_board) self.treeview_game.tree_updated.connect(self._handleTreeUpdated) self._stacksize_compound.spinbox_stacksize.setValue(500) self._stacksize_compound.spinbox_stacksize.valueChanged.connect(self._handleSpinboxChange) self.dofp_compound.button_execute.setEnabled(False) self.dofp_compound.button_execute.clicked.connect(self._executeFP) selection_model = self.treeview_game.selectionModel() selection_model.selectionChanged.connect(self._handleSelectionChanged) layout = QGridLayout() control_layout = QHBoxLayout() control_layout.addWidget(self._stacksize_compound) control_layout.addWidget(self.combobox_compound) control_layout.addWidget(self.dofp_compound) control_layout.addStretch() row = 0; col = 0; layout.addLayout(control_layout, row, col, 1, 2) row += 1; col = 0 layout.addWidget(self.treeview_game, row, col, 1, 2) self.setLayout(layout) self.setWindowTitle("Game Tree Viewer") self._setupContextMenu()
def initUI(self): title = QLabel('Title') author = QLabel('Author') review = QLabel('Review') titleEdit = QLineEdit() authorEdit = QLineEdit() reviewEdit = QTextEdit() btnOk = QtGui.QPushButton('OK') btnCancel = QtGui.QPushButton('Cancel') btnCancel.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addStretch(1) hbox.addWidget(btnOk) hbox.addWidget(btnCancel) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(title, 1, 0) grid.addWidget(titleEdit, 1, 1) grid.addWidget(author, 2, 0) grid.addWidget(authorEdit, 2, 1) grid.addWidget(review, 3, 0) grid.addWidget(reviewEdit, 3, 1, 5, 1) grid.addLayout(hbox, 8, 1) self.setLayout(grid) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Review') self.setWindowIcon(QtGui.QIcon('kpdf.png')) self.show()
def _createLayout(self): 'Create the Widget Layout' self._txtLogbook = QLineEdit() self._txtLogbook.setReadOnly(True) self._lblLogbook = QLabel(self.tr('&Logbook File:')) self._lblLogbook.setBuddy(self._txtLogbook) self._btnBrowse = QPushButton('...') self._btnBrowse.clicked.connect(self._btnBrowseClicked) self._btnBrowse.setStyleSheet('QPushButton { min-width: 24px; max-width: 24px; }') self._btnBrowse.setToolTip(self.tr('Browse for a Logbook')) self._cbxComputer = QComboBox() self._lblComputer = QLabel(self.tr('Dive &Computer:')) self._lblComputer.setBuddy(self._cbxComputer) self._btnAddComputer = QPushButton(QPixmap(':/icons/list-add.png'), self.tr('')) self._btnAddComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }') self._btnAddComputer.clicked.connect(self._btnAddComputerClicked) self._btnRemoveComputer = QPushButton(QPixmap(':/icons/list-remove.png'), self.tr('')) self._btnRemoveComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }') self._btnRemoveComputer.clicked.connect(self._btnRemoveComputerClicked) hbox = QHBoxLayout() hbox.addWidget(self._btnAddComputer) hbox.addWidget(self._btnRemoveComputer) gbox = QGridLayout() gbox.addWidget(self._lblLogbook, 0, 0) gbox.addWidget(self._txtLogbook, 0, 1) gbox.addWidget(self._btnBrowse, 0, 2) gbox.addWidget(self._lblComputer, 1, 0) gbox.addWidget(self._cbxComputer, 1, 1) gbox.addLayout(hbox, 1, 2) gbox.setColumnStretch(1, 1) self._pbTransfer = QProgressBar() self._pbTransfer.reset() self._txtStatus = QTextEdit() self._txtStatus.setReadOnly(True) self._btnTransfer = QPushButton(self.tr('&Transfer Dives')) self._btnTransfer.clicked.connect(self._btnTransferClicked) self._btnExit = QPushButton(self.tr('E&xit')) self._btnExit.clicked.connect(self.close) hbox = QHBoxLayout() hbox.addWidget(self._btnTransfer) hbox.addStretch() hbox.addWidget(self._btnExit) vbox = QVBoxLayout() vbox.addLayout(gbox) vbox.addWidget(self._pbTransfer) vbox.addWidget(self._txtStatus) vbox.addLayout(hbox) self.setLayout(vbox)
def __init__(self): super().__init__() if separate_colorbars: if rescale_colorbars: self.vmins = tuple(np.min(u[0]) for u in U) self.vmaxs = tuple(np.max(u[0]) for u in U) else: self.vmins = tuple(np.min(u) for u in U) self.vmaxs = tuple(np.max(u) for u in U) else: if rescale_colorbars: self.vmins = (min(np.min(u[0]) for u in U),) * len(U) self.vmaxs = (max(np.max(u[0]) for u in U),) * len(U) else: self.vmins = (min(np.min(u) for u in U),) * len(U) self.vmaxs = (max(np.max(u) for u in U),) * len(U) layout = QHBoxLayout() plot_layout = QGridLayout() self.colorbarwidgets = [cbar_widget(self, vmin=vmin, vmax=vmax) if cbar_widget else None for vmin, vmax in zip(self.vmins, self.vmaxs)] plots = [widget(self, grid, vmin=vmin, vmax=vmax, bounding_box=bounding_box, codim=codim) for vmin, vmax in zip(self.vmins, self.vmaxs)] if legend: for i, plot, colorbar, l in zip(range(len(plots)), plots, self.colorbarwidgets, legend): subplot_layout = QVBoxLayout() caption = QLabel(l) caption.setAlignment(Qt.AlignHCenter) subplot_layout.addWidget(caption) if not separate_colorbars or backend == 'matplotlib': subplot_layout.addWidget(plot) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) if colorbar: hlayout.addWidget(colorbar) subplot_layout.addLayout(hlayout) plot_layout.addLayout(subplot_layout, int(i/columns), (i % columns), 1, 1) else: for i, plot, colorbar in zip(range(len(plots)), plots, self.colorbarwidgets): if not separate_colorbars or backend == 'matplotlib': plot_layout.addWidget(plot, int(i/columns), (i % columns), 1, 1) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) if colorbar: hlayout.addWidget(colorbar) plot_layout.addLayout(hlayout, int(i/columns), (i % columns), 1, 1) layout.addLayout(plot_layout) if not separate_colorbars: layout.addWidget(self.colorbarwidgets[0]) for w in self.colorbarwidgets[1:]: w.setVisible(False) self.setLayout(layout) self.plots = plots
def __init__(self): QWidget.__init__(self) self.__view_page_select = ViewPageSelectMag() self.__view_widget_select = ViewWidgetSelect() self.__widget_data = dict() # 主 layout _layout = QGridLayout() self.setLayout(_layout) # 控件类型 _type_label = QLabel(u"对象类型") self.__type_select = OrcSelect("operate_object_type") # 控件信息输入 _widget_label = QLabel(u"控件") self.__widget_input = OrcLineEdit() self.__widget_input.setReadOnly(True) # 操作信息输入 layout _operate_label = QLabel(u"操作") self.__operate_select = SelectWidgetOperation() # 按钮 _button_submit = QPushButton(u"确定") _button_cancel = QPushButton(u"取消") # 按钮 layout _layout_button = QHBoxLayout() _layout_button.addStretch() _layout_button.addWidget(_button_submit) _layout_button.addWidget(_button_cancel) _layout.addWidget(_type_label, 0, 0) _layout.addWidget(self.__type_select, 0, 1) _layout.addWidget(_widget_label, 1, 0) _layout.addWidget(self.__widget_input, 1, 1) _layout.addWidget(_operate_label, 2, 0) _layout.addWidget(self.__operate_select, 2, 1) _layout.addLayout(_layout_button, 3, 1) self.__change_type("PAGE") # connection _button_cancel.clicked.connect(self.close) _button_submit.clicked.connect(self.__submit) self.__widget_input.clicked.connect(self.__show_select) self.__view_widget_select.sig_selected[dict].connect(self.__set_widget) self.__view_page_select.sig_selected[dict].connect(self.__set_widget) self.__type_select.currentIndexChanged.connect(self.__change_type)
def __init__(self, current_tab_text=None, parent=None): """ Constructor """ super(DialogOtpWriteRange, self).__init__(parent) ok_button = QPushButton("&OK") cancel_button = QPushButton("Cancel") button_layout = QHBoxLayout() button_layout.addStretch() button_layout.addWidget(ok_button) button_layout.addWidget(cancel_button) layout = QGridLayout() current_row = 0 label_start = QLabel("starting address :") self.hsb_start = HexSpinBox() self.hsb_start.setMinimum(0x00) self.hsb_start.setMaximum(0x7F) self.hsb_start.setValue(0x00) layout.addWidget(label_start, current_row, 0) layout.addWidget(self.hsb_start, current_row, 1, 1, 1) current_row += 1 label_finish = QLabel("ending address :") self.hsb_finish = HexSpinBox() self.hsb_finish.setMinimum(0x00) self.hsb_finish.setMaximum(0x7F) self.hsb_finish.setValue(0x7F) layout.addWidget(label_finish, current_row, 0) layout.addWidget(self.hsb_finish, current_row, 1, 1, 1) # current_row += 1 # label_bank = QLabel("otp bank :") # self.spin_box_bank_sel = QSpinBox() # self.spin_box_bank_sel.setMinimum(0) # self.spin_box_bank_sel.setMaximum(1) # layout.addWidget(label_bank, current_row, 0) # layout.addWidget(self.spin_box_bank_sel, current_row, 1, 1, 1) current_row += 1 layout.addLayout(button_layout, current_row, 0, 1, 2) self.setLayout(layout) self.connect(ok_button, SIGNAL("clicked()"), self, SLOT("accept()")) self.connect(cancel_button, SIGNAL("clicked()"), self, SLOT("reject()")) self.setWindowTitle("set OTP write range / bank")
def __init__(self): super(PlotWidget, self).__init__() if separate_colorbars: vmins = tuple(np.min(u) for u in U) vmaxs = tuple(np.max(u) for u in U) else: vmins = (min(np.min(u) for u in U),) * len(U) vmaxs = (max(np.max(u) for u in U),) * len(U) layout = QHBoxLayout() plot_layout = QGridLayout() plots = [widget(self, grid, vmin=vmin, vmax=vmax, bounding_box=bounding_box, codim=codim) for vmin, vmax in izip(vmins, vmaxs)] if legend: for i, plot, l in izip(xrange(len(plots)), plots, legend): subplot_layout = QVBoxLayout() caption = QLabel(l) caption.setAlignment(Qt.AlignHCenter) subplot_layout.addWidget(caption) if not separate_colorbars or backend == 'matplotlib': subplot_layout.addWidget(plot) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) hlayout.addWidget(ColorBarWidget(self, vmin=vmins[i], vmax=vmaxs[i])) subplot_layout.addLayout(hlayout) plot_layout.addLayout(subplot_layout, int(i/2), (i % 2), 1, 1) else: for i, plot in enumerate(plots): if not separate_colorbars or backend == 'matplotlib': plot_layout.addWidget(plot, int(i/2), (i % 2), 1, 1) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) hlayout.addWidget(ColorBarWidget(self, vmin=vmins[i], vmax=vmaxs[i])) plot_layout.addLayout(plot, int(i/2), (i % 2), 1, 1) layout.addLayout(plot_layout) if not separate_colorbars: layout.addWidget(ColorBarWidget(self, vmin=vmin, vmax=vmax)) self.setLayout(layout) self.plots = plots
def __init__(self, parent=None): super(AddFilterDlg, self).__init__(parent) self.setWindowTitle("Advanced Filtering Options") note_label = QLabel("NOTE: These filtering options apply exclusively to relief devices, not to the relief device area they belong to or to their scenarios.") pressure_label = QLabel("Filter where <b>Set Pressure</b> is") self.pressure_combobox = QComboBox() self.pressure_combobox.addItems(["Greater Than", "Less Than", "Equal To", "Not Equal To"]) self.pressure_value = QDoubleSpinBox() pressure_layout = QHBoxLayout() pressure_layout.addWidget(pressure_label) pressure_layout.addWidget(self.pressure_combobox) pressure_layout.addWidget(self.pressure_value) button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) layout = QGridLayout() layout.addWidget(note_label, 0, 0) layout.addLayout(pressure_layout, 1, 0) layout.addWidget(button_box, 2, 0) self.setLayout(layout) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject)
def testInternalRef(self): mw = QWidget() w = QWidget() ow = QWidget() topLayout = QGridLayout() # unique reference self.assertEqual(getrefcount(w), 2) self.assertEqual(getrefcount(ow), 2) topLayout.addWidget(w, 0, 0) topLayout.addWidget(ow, 1, 0) # layout keep the referemce self.assertEqual(getrefcount(w), 3) self.assertEqual(getrefcount(ow), 3) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 1, 0, 1, 4) # the same reference self.assertEqual(getrefcount(w), 3) self.assertEqual(getrefcount(ow), 3) mw.setLayout(mainLayout) # now trasfer the ownership to mw self.assertEqual(getrefcount(w), 3) self.assertEqual(getrefcount(ow), 3) del mw # remove the ref and invalidate the widget self.assertEqual(getrefcount(w), 2) self.assertEqual(getrefcount(ow), 2)
def __init__(self, title, mainWindow): super(ScreenWithBackButton, self).__init__() self.title = title self.mainWindow = mainWindow layout = QGridLayout() title = QLabel(title) title.setStyleSheet("font-size: 48px;") title.setAlignment(Qt.AlignCenter) layout.addWidget(title, 0, 0, 1, 7) layout.addLayout(self.makeContent(), 1, 0, 1, 7) b = ExpandingButton() b.setText("Back") b.setIcon(QIcon(":icons/go-previous")) b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.clicked.connect(mainWindow.stepBack) layout.addWidget(b, 2, 0, 1, 3) layout.setRowStretch(0, 1) layout.setRowStretch(1, 6) layout.setRowStretch(2, 1) self.setLayout(layout)
def layoutWidgets(self): vbox = QVBoxLayout() grid = QGridLayout() grid.addLayout(self.topLeftForm, 0, 0) grid.addLayout(self.topRightForm, 0, 1) grid.addLayout(self.startForm, 1, 0) grid.addLayout(self.endForm, 1, 1) vbox.addLayout(grid) vbox.addStretch() self.setLayout(vbox) self.setTabOrder(self.stdFontStartEdit, self.stdFontEndEdit) self.setTabOrder(self.altFontStartEdit, self.altFontEndEdit) self.setTabOrder(self.monoFontStartEdit, self.monoFontEndEdit) self.setTabOrder(self.boldStartEdit, self.boldEndEdit) self.setTabOrder(self.italicStartEdit, self.italicEndEdit) self.setTabOrder(self.subscriptStartEdit, self.subscriptEndEdit) self.setTabOrder(self.superscriptStartEdit, self.superscriptEndEdit) self.setTabOrder(self.underlineStartEdit, self.underlineEndEdit) self.setTabOrder(self.strikeoutStartEdit, self.strikeoutEndEdit)
class ImageViewer(QWidget): def __init__(self, filename=None, name=None, parent=None): super(ImageViewer, self).__init__(parent) self.imageRaw = np.zeros((200, 200, 200)) self.imageRGB = np.zeros((200, 200, 200, 3)) self.viewRange = [[100, 100], [100, 100], [100, 100]] self.zoomFactors = [3.0, 3.0, 3.0] self.iMin = 0 self.iMax = 1000 self.ijk = [0, 0, 0] self.name = 'untitled' self.initHbRL() self.mouseCursorCross = False ## Upper buttons self.upperRow = QHBoxLayout() self.drawRightHb = QPushButton('RightHb', self) self.drawLeftHb = QPushButton('LeftHb', self) self.drawRightHb.setCheckable(True) self.drawLeftHb.setCheckable(True) self.upperRow.addWidget(self.drawRightHb) self.upperRow.addWidget(self.drawLeftHb) QtCore.QObject.connect(self.drawRightHb, QtCore.SIGNAL('clicked()'), self.clickRightHb) QtCore.QObject.connect(self.drawLeftHb, QtCore.SIGNAL('clicked()'), self.clickLeftHb) ## View Layout self.scenes = [ MyGraphicsScene(self, 0), MyGraphicsScene(self, 1), MyGraphicsScene(self, 2) ] self.views = [ QGraphicsView(self.scenes[0]), QGraphicsView(self.scenes[1]), QGraphicsView(self.scenes[2]) ] self.sceneItems = [None, None, None] #Scene 4 view4 = QGridLayout() labelX = QLabel('X: ') labelY = QLabel('Y: ') labelZ = QLabel('Z: ') self.spin = [QSpinBox(), QSpinBox(), QSpinBox()] labelMinIntensity = QLabel('Min: ') labelMaxIntensity = QLabel('Max: ') labelZoom = QLabel('Zoom: ') self.spinMin = QSpinBox() self.spinMax = QSpinBox() self.spinZoom = QSpinBox() self.spinMin.setMaximum(10000) self.spinMax.setMaximum(10000) self.spinMin.setValue(self.iMin) self.spinMax.setValue(self.iMax) self.spinZoom.setValue(self.zoomFactors[0]) self.spinMin.setKeyboardTracking(False) self.spinMin.valueChanged.connect(self.setIntensity) self.spinMax.setKeyboardTracking(False) self.spinMax.valueChanged.connect(self.setIntensityMax) self.spinZoom.valueChanged.connect(self.setZoomFactor) self.spinZoom.setKeyboardTracking(False) labelAreaR = QLabel('Right: ') labelAreaL = QLabel('Left: ') self.labelAreaValueR = QLabel() self.labelAreaValueL = QLabel() view4.addWidget(labelX, 0, 0, 2, 1) view4.addWidget(labelY, 1, 0, 2, 1) view4.addWidget(labelZ, 2, 0, 2, 1) view4.addWidget(labelMinIntensity, 4, 0, 2, 1) view4.addWidget(labelMaxIntensity, 5, 0, 2, 1) view4.addWidget(labelZoom, 6, 0, 2, 1) view4.addWidget(labelAreaR, 7, 0) view4.addWidget(labelAreaL, 7, 2) view4.addWidget(self.spin[0], 0, 2, 2, 1) view4.addWidget(self.spin[1], 1, 2, 2, 1) view4.addWidget(self.spin[2], 2, 2, 2, 1) view4.addWidget(self.spinMin, 4, 2, 2, 1) view4.addWidget(self.spinMax, 5, 2, 2, 1) view4.addWidget(self.spinZoom, 6, 2, 2, 1) view4.addWidget(self.labelAreaValueR, 7, 1) view4.addWidget(self.labelAreaValueL, 7, 3) self.viewLayout = QGridLayout() self.viewLayout.addWidget(self.views[0], 0, 0) self.viewLayout.addWidget(self.views[1], 0, 1) self.viewLayout.addWidget(self.views[2], 1, 0) self.viewLayout.addLayout(view4, 1, 1) ## Lower self.lowerRow = QHBoxLayout() calculateButtonDown = QPushButton('calculateVolume', self) saveButtonDown = QPushButton('SaveHb', self) loadButtonDown = QPushButton('loadHb', self) savepngButtonDown = QPushButton('Save PNG', self) self.lowerRow.addWidget(calculateButtonDown) self.lowerRow.addWidget(saveButtonDown) self.lowerRow.addWidget(loadButtonDown) self.lowerRow.addWidget(savepngButtonDown) QtCore.QObject.connect(calculateButtonDown, QtCore.SIGNAL('clicked()'), self.getHbAreas) QtCore.QObject.connect(saveButtonDown, QtCore.SIGNAL('clicked()'), self.saveHb) QtCore.QObject.connect(loadButtonDown, QtCore.SIGNAL('clicked()'), self.loadHb) QtCore.QObject.connect(savepngButtonDown, QtCore.SIGNAL('clicked()'), self.saveCoronalSlice) ## Layout self.mainLayout = QVBoxLayout() self.mainLayout.addLayout(self.upperRow) self.mainLayout.addLayout(self.viewLayout) self.mainLayout.addLayout(self.lowerRow) self.setLayout(self.mainLayout) self.setWindowTitle("Image Viewer") self.resize(600, 700) self.show() if filename: self.loadNifti1(filename, name=name) def loadNifti1(self, filename, name=None): self.loadImage = LoadImage() self.loadImage.readNifti1(filename) if name is None: name = filename[:] if name[-7:] == '.nii.gz': name = name[:-7] elif name[-4:] == '.nii': name = name[:-4] for ch in ['/', '.', '~']: pos = name.find(ch) while pos > -1: name = '%s_%s' % (name[:pos], name[pos + 1:]) pos = name.find(ch) self.name = name self.imageRaw = self.loadImage.data self.spinMin.setMaximum(int(self.imageRaw.max() * 1.2)) self.spinMax.setMaximum(int(self.imageRaw.max() * 1.2)) #self.iMin = int(max(0, self.imageRaw.min()*1.2)) self.iMin = 0 self.iMax = int(self.imageRaw.max() * 0.8) self.spinMin.setValue(self.iMin) self.spinMax.setValue(self.iMax) self.imageRGB = convertImageRGB( resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax)) self.setIJK() self.drawBaseImage() self.setSceneIJK() self.showSpinValue() self.setMouseCursor(True) def showSpinValue(self): self.spin[0].setMaximum(self.imageRaw.shape[0]) self.spin[1].setMaximum(self.imageRaw.shape[1]) self.spin[2].setMaximum(self.imageRaw.shape[2]) self.spin[0].setKeyboardTracking(False) self.spin[1].setKeyboardTracking(False) self.spin[2].setKeyboardTracking(False) self.spin[0].setValue(self.ijk[0]) self.spin[1].setValue(self.ijk[1]) self.spin[2].setValue(self.ijk[2]) self.spin[0].valueChanged.connect(self.resetI) self.spin[1].valueChanged.connect(self.resetJ) self.spin[2].valueChanged.connect(self.resetK) def resetI(self, i): self.ijk[0] = i self.drawBaseImage([0]) def resetJ(self, j): self.ijk[1] = j self.drawBaseImage([1]) self.labelAreaValueR.clear() self.labelAreaValueL.clear() def resetK(self, k): self.ijk[2] = k self.drawBaseImage([2]) def initHbRL(self): self.hbRight = { 'name': 'HbRight', 'color': 'red', 'images': [], 'points': [] } self.hbLeft = { 'name': 'HbLeft', 'color': 'blue', 'images': [], 'points': [] } def clickRightHb(self): if self.drawLeftHb.isChecked(): self.drawLeftHb.setChecked(False) def clickLeftHb(self): if self.drawRightHb.isChecked(): self.drawRightHb.setChecked(False) def saveHb(self, filename=None): if filename is None: filename = '%s_lawson_hb.csv' % self.name writeHb(filename, self.hbRight, self.hbLeft) with open(filename, 'a') as fout: volumes = self.getHbAreas() fout.write('%s,%s\n' % (volumes[0], volumes[1])) png_filename = filename[:-4] def saveCoronalSlice(self, filename=None): viewIndex = 1 if filename is None: filename = '%s_lawson_hb' % self.name filename += str('%03d.png' % self.ijk[viewIndex]) self.scenes[viewIndex].savePng(filename, 'PNG') def loadHb(self, filename=None): if filename is None: filename = '%s_lawson_hb.csv' % self.name self.initHbRL() readHb(filename, self.hbRight, self.hbLeft) def setMouseCursor(self, cross=False): if cross != self.mouseCursorCross: self.mouseCursorCross = cross if cross: #self.setCursor(QCursor(QtCore.Qt.CrossCursor)) self.setCursor(QtCore.Qt.CrossCursor) else: #self.setCursor(QCursor(QtCore.Qt.ArrowCursor)) self.setCursor(QtCore.Qt.ArrowCursor) def getZoomFactors(self): return self.zoomFactors def magZoomFactors(self, ratio): self.setZoomFactors([value + ratio for value in self.zoomFactors]) self.spinZoom.setValue(self.zoomFactors[0]) def setZoomFactors(self, zoomFactors): sceneRects = self.saveScene() self.zoomFactors = zoomFactors self.drawBaseImage() self.restoreScene(sceneRects) def setZoomFactor(self, zoomFactor): self.setZoomFactors([zoomFactor, zoomFactor, zoomFactor]) def getIntensity(self): return self.iMin, self.iMax def setIntensityMax(self, iMax): self.setIntensity(iMax=iMax) def setIntensity(self, iMin=None, iMax=None): if iMin: self.iMin = iMin if iMax: self.iMax = iMax self.imageRGB = convertImageRGB( resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax)) self.drawBaseImage() def mousePressEventLeft(self, viewIndex, x, y): if viewIndex == 1: if self.drawRightHb.isChecked(): hbDict = self.hbRight labelAreaValue = self.labelAreaValueR elif self.drawLeftHb.isChecked(): hbDict = self.hbLeft labelAreaValue = self.labelAreaValueL else: self.resetIJK(viewIndex, x, y) return if not hbDict.has_key(self.ijk[viewIndex]): hbDict[self.ijk[viewIndex]] = HbRegionDraw() if hbDict[self.ijk[viewIndex]].insert == 4: for item in hbDict['images']: # lines self.scenes[viewIndex].removeItem(item) hbDict['images'] = [] item = hbDict['points'].pop(0) # last point self.scenes[viewIndex].removeItem(item) i, j = self.point2fijk(viewIndex, x, y) if not hbDict[self.ijk[viewIndex]].push((i, j)): item = hbDict['points'].pop(0) # last point self.scenes[viewIndex].removeItem(item) #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0]) x_round, y_round = self.ij2point(viewIndex, i, j) hbDict['points'].insert( 0, self.scenes[viewIndex].addEllipse( x_round - 1, y_round - 1, 2, 2, pen=QPen(QColor(hbDict['color'])))) if hbDict[self.ijk[viewIndex]].insert >= 4: area = hbDict[self.ijk[viewIndex]].calculate_area( hbDict['name']) print ' %s %s: %s' % (self.ijk[viewIndex], hbDict['name'], area) self.drawHb(hbDict) #labelAreaValue.setText('%s: %3.2f' % (self.ijk[viewIndex], area)) labelAreaValue.setText('%3.2f' % (area)) else: self.resetIJK(viewIndex, x, y) def mousePressEventRight(self, viewIndex, x, y): if viewIndex == 1: if self.drawRightHb.isChecked(): hbDict = self.hbRight elif self.drawLeftHb.isChecked(): hbDict = self.hbLeft else: return if not hbDict.has_key(self.ijk[viewIndex]): return if hbDict[self.ijk[viewIndex]].insert == 4: for item in hbDict['images']: # lines self.scenes[viewIndex].removeItem(item) hbDict['images'] = [] #for item in self.scenes[viewIndex].items()[:3]: # lines # self.scenes[viewIndex].removeItem(item) if hbDict[self.ijk[viewIndex]].pop(): item = hbDict['points'].pop(0) # last point self.scenes[viewIndex].removeItem(item) #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0]) def moveIJK(self, viewIndex, dx): self.ijk[viewIndex] += dx self.spin[viewIndex].setValue(self.ijk[viewIndex]) self.drawBaseImage([viewIndex]) self.labelAreaValueR.clear() self.labelAreaValueL.clear() def point2fijk(self, viewIndex, x, y): indexTable = [[1, 2], [0, 2], [0, 1]] xIndex = indexTable[viewIndex][0] yIndex = indexTable[viewIndex][1] ijkX = float(x) / self.zoomFactors[viewIndex] ijkY = self.imageRGB.shape[yIndex] - 1 - float( y) / self.zoomFactors[viewIndex] ijkX = np.round(ijkX * 2) / 2 ijkY = np.round(ijkY * 2) / 2 return (ijkX, ijkY) def point2fijk_flt(self, viewIndex, x, y): indexTable = [[1, 2], [0, 2], [0, 1]] xIndex = indexTable[viewIndex][0] yIndex = indexTable[viewIndex][1] ijkX = float(x) / self.zoomFactors[viewIndex] ijkY = self.imageRGB.shape[yIndex] - 1 - float( y) / self.zoomFactors[viewIndex] return (ijkX, ijkY) def point2ijk(self, viewIndex, x, y): indexTable = [[1, 2], [0, 2], [0, 1]] xIndex = indexTable[viewIndex][0] yIndex = indexTable[viewIndex][1] ijkX = int(x / self.zoomFactors[viewIndex]) ijkY = self.imageRGB.shape[yIndex] - 1 - int( y / self.zoomFactors[viewIndex]) return (ijkX, ijkY) def ij2point(self, viewIndex, i, j): indexTable = [[1, 2], [0, 2], [0, 1]] xIndex = indexTable[viewIndex][0] yIndex = indexTable[viewIndex][1] pointX = i * self.zoomFactors[viewIndex] pointY = (self.imageRGB.shape[yIndex] - 1 - j) * self.zoomFactors[viewIndex] return (pointX, pointY) def resetIJK(self, viewIndex, x, y): indexTable = [[1, 2], [0, 2], [0, 1]] xIndex = indexTable[viewIndex][0] yIndex = indexTable[viewIndex][1] self.ijk[xIndex] = int(x / self.zoomFactors[viewIndex]) self.ijk[yIndex] = self.imageRGB.shape[yIndex] - 1 - int( y / self.zoomFactors[viewIndex]) self.spin[xIndex].setValue(self.ijk[xIndex]) self.spin[yIndex].setValue(self.ijk[yIndex]) self.drawBaseImage(indexTable[viewIndex]) self.labelAreaValueR.clear() self.labelAreaValueL.clear() def saveScene(self): sceneRects = [0, 0, 0] for i in range(3): size = self.views[i].size().toTuple() x, y, _, _ = self.scenes[i].sceneRect().getRect() x += (size[0] - 10) / 2.0 y += (size[1] - 10) / 2.0 x /= self.zoomFactors[i] y /= self.zoomFactors[i] sceneRects[i] = [x, y] return sceneRects def restoreScene(self, sceneRects): for i in range(3): size = self.views[i].size().toTuple() x = sceneRects[i][0] * self.zoomFactors[i] y = sceneRects[i][1] * self.zoomFactors[i] self.scenes[i].setSceneRect(x - (size[0] - 10) / 2, y - (size[0] - 10) / 2, size[0] - 10, size[1] - 10) def setSceneIJK(self, viewIndex=(0, 1, 2)): for i in viewIndex: size = self.views[i].size().toTuple() xyCenter = [ self.ijk[tmp] * self.zoomFactors[i] for tmp in range(3) if tmp is not i ] self.scenes[i].setSceneRect(xyCenter[0] - size[0] / 2.0, xyCenter[1] - size[1] / 2.0, size[0] - 10, size[1] - 10) def setIJK(self, ijk='center'): if ijk == 'center': self.ijk = [ self.imageRGB.shape[0] / 2, self.imageRGB.shape[1] / 2, self.imageRGB.shape[2] / 2 ] else: self.ijk = ijk self.spin[0].setValue(self.ijk[0]) self.spin[1].setValue(self.ijk[1]) self.spin[2].setValue(self.ijk[2]) def get2D(self, plane): if plane == 0: return np.rot90(self.imageRGB[self.ijk[0], :, :, :]) elif plane == 1: return np.rot90(self.imageRGB[:, self.ijk[1], :, :]) elif plane == 2: return np.rot90(self.imageRGB[:, :, self.ijk[2], :]) def drawBaseImage(self, viewIndex=(0, 1, 2), eraseOthers=True): for i in viewIndex: imageArray3d = self.get2D(i) height, width, bytesPerComponent = imageArray3d.shape imageArray = imageArray3d.flatten() bytesPerLine = bytesPerComponent * width image = QImage(imageArray, width, height, bytesPerLine, QImage.Format_RGB888) #image = image.scaled( int(width*self.zoomFactors[i]), int(height*self.zoomFactors[i]), Qt.KeepAspectRatio, Qt.SmoothTransformation) image = image.scaled(int(width * self.zoomFactors[i]), int(height * self.zoomFactors[i]), QtCore.Qt.KeepAspectRatio) if self.sceneItems[i] is not None: #self.scenes[i].removeItem(self.sceneItems[i]) self.sceneItems[i].setPixmap(QPixmap.fromImage(image)) if False: items = self.scenes[i].items() for item in items: self.scenes[i].removeItem(item) self.sceneItems[i] = self.scenes[i].addPixmap( QPixmap.fromImage(image)) for item in items[1:]: self.scenes[i].additem(item) del items else: self.sceneItems[i] = self.scenes[i].addPixmap( QPixmap.fromImage(image)) if eraseOthers: for item in self.scenes[i].items(): if item != self.sceneItems[i]: self.scenes[i].removeItem(item) # TODO: where to put this self.drawHbPts(self.hbRight) self.drawHb(self.hbRight) self.drawHbPts(self.hbLeft) self.drawHb(self.hbLeft) def drawHbPts(self, hbDict): viewIndex = 1 if not hbDict.has_key(self.ijk[viewIndex]): return pts = [ self.ij2point(viewIndex, i, j) for (i, j) in hbDict[self.ijk[viewIndex]].get_points() ] for i in range(hbDict[self.ijk[viewIndex]].insert): hbDict['points'].insert( 0, self.scenes[viewIndex].addEllipse( pts[i][0] - 1, pts[i][1] - 1, 2, 2, pen=QPen(QColor(hbDict['color'])))) def drawHb(self, hbDict): viewIndex = 1 if not hbDict.has_key(self.ijk[viewIndex]): return if hbDict[self.ijk[viewIndex]].insert < 4: return a, b, c, d = [ self.ij2point(viewIndex, i, j) for (i, j) in hbDict[self.ijk[viewIndex]].get_points() ] cp = hbDict[self.ijk[viewIndex]].cp cp = self.ij2point(viewIndex, cp[0], cp[1]) vA = (a[0] - cp[0], a[1] - cp[1]) vB = (b[0] - cp[0], b[1] - cp[1]) vD = (d[0] - cp[0], d[1] - cp[1]) arcAD = QPainterPath() arcDB = QPainterPath() if hbDict['name'] == 'HbRight': sign = 1 startAngle = 0 else: sign = -1 startAngle = 180 angleADlad = sign * angleBw2Vectors(vA, vD) angleAD = 180 / np.pi * angleADlad if vD[0] * vD[0] + vD[1] * vD[1] >= vA[0] * vA[0] + vA[1] * vA[1]: rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0) coefA = rotD[0] rotA = rotateVector(vA, angleADlad) coefB = np.sqrt(coefA * coefA / (coefA * coefA - rotA[0] * rotA[0]) * rotA[1] * rotA[1]) eccentricAnomalyAD = -180 / np.pi * np.arctan( coefA / coefB * np.tan(angleADlad)) arcAD.moveTo(cp[0] + sign * coefA, cp[1]) arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB, startAngle, eccentricAnomalyAD) else: rotA = (np.sqrt(vA[0] * vA[0] + vA[1] * vA[1]), 0) coefA = rotA[0] angleDAlad = sign * angleBw2Vectors(vD, vA) angleDA = 180 / np.pi * angleDAlad rotD = vD coefB = np.sqrt(coefA * coefA / (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] * rotD[1]) eccentricAnomalyDA = 180 / np.pi * np.arctan( coefA / coefB * np.tan(angleDAlad)) arcAD.moveTo(cp[0] + sign * coefA, cp[1]) arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB, startAngle, eccentricAnomalyDA) angleAD = 0.0 if vD[0] * vD[0] + vD[1] * vD[1] >= vB[0] * vB[0] + vB[1] * vB[1]: rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0) coefA = rotD[0] angleBDlad = sign * angleBw2Vectors(vD, vB) angleBD = 180 / np.pi * angleBDlad rotB = rotateVector(vB, angleADlad) coefB = np.sqrt(coefA * coefA / (coefA * coefA - rotB[0] * rotB[0]) * rotB[1] * rotB[1]) eccentricAnomalyDB = 180 / np.pi * np.arctan( coefA / coefB * np.tan(angleBDlad)) arcDB.moveTo(cp[0] + sign * coefA, cp[1]) arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB, startAngle, eccentricAnomalyDB) angleAB = 180 / np.pi * sign * angleBw2Vectors(vA, vD) else: rotB = (np.sqrt(vB[0] * vB[0] + vB[1] * vB[1]), 0) coefA = rotB[0] angleABlad = sign * angleBw2Vectors(vA, vB) angleAB = 180 / np.pi * angleABlad angleDBlad = sign * angleBw2Vectors(vD, vB) angleDB = 180 / np.pi * angleDBlad rotD = rotateVector(vD, angleABlad) coefB = np.sqrt(coefA * coefA / (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] * rotD[1]) eccentricAnomalyDB = -180 / np.pi * np.arctan( coefA / coefB * np.tan(angleDBlad)) arcDB.moveTo(cp[0] + sign * coefA, cp[1]) arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB, startAngle, eccentricAnomalyDB) imgAC = self.scenes[viewIndex].addLine(a[0], a[1], cp[0], cp[1], pen=QPen(QColor( hbDict['color']))) imgBC = self.scenes[viewIndex].addLine(b[0], b[1], c[0], c[1], pen=QPen(QColor( hbDict['color']))) imgAD = self.scenes[viewIndex].addPath(arcAD, pen=QPen(QColor( hbDict['color']))) imgAD.setTransform(QTransform().translate( cp[0], cp[1]).rotate(-angleAD).translate(-cp[0], -cp[1])) imgDB = self.scenes[viewIndex].addPath(arcDB, pen=QPen(QColor( hbDict['color']))) imgDB.setTransform(QTransform().translate( cp[0], cp[1]).rotate(-angleAB).translate(-cp[0], -cp[1])) hbDict['images'] = [imgAD, imgDB, imgBC, imgAC] def getHbAreas(self): volumes = [] for hbDict in [self.hbRight, self.hbLeft]: keys = hbDict.keys() if not keys: volumes.append(0.0) continue print 'Calculate %s Volume...' % hbDict['name'] unit = self.loadImage.zooms[0] * self.loadImage.zooms[ 1] * self.loadImage.zooms[2] volume = 0.0 keys.sort() for key in keys: if type(key) == type(''): continue area = hbDict[key].area print ' %s: %s (voxel)' % (key, area) volume += area volume *= unit print 'volume = %s (mm^3)' % volume volumes.append(volume) return volumes
def setupUi(self): gridlayout = QGridLayout() self.setLayout(gridlayout) ''' Buttons added to inputs should have a numeric ID set equal to their input number on the Aldates main switcher. ''' self.inputs = QButtonGroup() inputsGrid = QHBoxLayout() self.btnCamera1 = CameraSelectionButton(1) self.btnCamera1.setText("Camera 1") self.btnCamera1.setInput(VisualsSystem.camera1) inputsGrid.addWidget(self.btnCamera1) self.inputs.addButton(self.btnCamera1, 1) self.btnCamera1.setIcon(QIcon(":icons/camera-video")) self.btnCamera2 = CameraSelectionButton(2) self.btnCamera2.setText("Camera 2") self.btnCamera2.setInput(VisualsSystem.camera2) inputsGrid.addWidget(self.btnCamera2) self.inputs.addButton(self.btnCamera2, 2) self.btnCamera2.setIcon(QIcon(":icons/camera-video")) self.btnCamera3 = CameraSelectionButton(3) self.btnCamera3.setText("Camera 3") self.btnCamera3.setInput(VisualsSystem.camera3) inputsGrid.addWidget(self.btnCamera3) self.inputs.addButton(self.btnCamera3, 3) self.btnCamera3.setIcon(QIcon(":icons/camera-video")) self.btnDVD = InputButton() self.btnDVD.setText("DVD") self.btnDVD.setInput(VisualsSystem.dvd) inputsGrid.addWidget(self.btnDVD) self.inputs.addButton(self.btnDVD, 4) self.btnDVD.setIcon(QIcon(":icons/media-optical")) self.btnExtras = InputButton() self.btnExtras.setText("Extras") inputsGrid.addWidget(self.btnExtras) self.btnExtras.setIcon(QIcon(":icons/video-display")) self.inputs.addButton(self.btnExtras, 5) self.btnVisualsPC = InputButton() self.btnVisualsPC.setText("Visuals PC") self.btnVisualsPC.setInput(VisualsSystem.visualsPC) inputsGrid.addWidget(self.btnVisualsPC) self.inputs.addButton(self.btnVisualsPC, 6) self.btnVisualsPC.setIcon(QIcon(":icons/computer")) self.btnBlank = InputButton() self.btnBlank.setText("Blank") self.btnBlank.setInput(VisualsSystem.blank) inputsGrid.addWidget(self.btnBlank) self.inputs.addButton(self.btnBlank, 0) gridlayout.addLayout(inputsGrid, 0, 0, 1, 7) self.extrasSwitcher = ExtrasSwitcher(self.controller) self.extrasSwitcher.inputSelected.connect(self.handleExtrasSelect) self.btnExtras.setInput(ProxyInput(self.extrasSwitcher)) self.blank = QWidget(self) gridlayout.addWidget(self.blank, 1, 0, 1, 5) self.outputsGrid = OutputsGrid() gridlayout.addWidget(self.outputsGrid, 1, 5, 1, 2) gridlayout.setRowStretch(0, 1) gridlayout.setRowStretch(1, 5) QMetaObject.connectSlotsByName(self) self.setInputClickHandlers() self.setOutputClickHandlers(self.outputsGrid) self.configureInnerControlPanels() self.gridlayout = gridlayout
def __init__(self, controller, joystickAdapter=None): super(MainWindow, self).__init__() self.controller = controller self.setWindowTitle("av-control") self.resize(1024, 600) self.setWindowIcon(QIcon(":icons/video-display")) atem = controller['ATEM'] self.switcherState = SwitcherState(atem) self.mainScreen = VideoSwitcher(controller, self, self.switcherState, joystickAdapter) # This is possibly a bad / too complicated idea... # self.mainScreen.setEnabled(self.switcherState.connected) # self.switcherState.connectionChanged.connect(self.mainScreen.setEnabled) self.stack = QStackedWidget() self.stack.addWidget(self.mainScreen) outer = QWidget() mainLayout = QGridLayout() mainLayout.addWidget(self.stack, 0, 0, 1, 7) column = 0 self.spc = SystemPowerWidget(controller, self) syspower = ExpandingButton() syspower.setText("Power") syspower.clicked.connect(self.showSystemPower) syspower.setIcon(QIcon(":icons/system-shutdown")) syspower.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(syspower, 1, column) column += 1 if controller.hasDevice("Blinds"): self.bc = BlindsControl(controller["Blinds"], self) blinds = ExpandingButton() blinds.setText("Blinds") blinds.clicked.connect(lambda: self.showScreen(self.bc)) blinds.setIcon(QIcon(":icons/blinds")) blinds.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(blinds, 1, column) column += 1 if controller.hasDevice("Lights"): self.lightsMenu = LightingControl(controller["Lights"], self) lights = ExpandingButton() lights.setText("Lights") lights.clicked.connect(lambda: self.showScreen(self.lightsMenu)) lights.setIcon(QIcon(":icons/lightbulb_on")) lights.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(lights, 1, column) column += 1 if controller.hasDevice("Recorder"): hyperdeck = controller['Recorder'] self.hyperdeckState = HyperdeckState(hyperdeck) self.recorderScreen = RecorderControl(hyperdeck, atem, self.hyperdeckState, self) recorder = ExpandingButton() recorder.setText("Recorder") recorder.setIcon(QIcon(":icons/drive-optical")) recorder.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) recorder.clicked.connect(lambda: self.showScreen(self.recorderScreen)) mainLayout.addWidget(recorder, 1, column) column += 1 def update_recorder_icon(transport): if 'status' in transport: if transport['status'] == TransportState.RECORD: recorder.setIcon(QIcon(":icons/media-record")) elif transport['status'] == TransportState.PLAYING: recorder.setIcon(QIcon(":icons/media-playback-start")) else: recorder.setIcon(QIcon(":icons/drive-optical")) self.hyperdeckState.transportChange.connect(update_recorder_icon) self.advMenu = AdvancedMenu(self.controller, self.switcherState.mixTransition, atem, self) adv = ExpandingButton() adv.setText("Advanced") adv.setIcon(QIcon(":icons/applications-system")) adv.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) adv.clicked.connect(lambda: self.showScreen(self.advMenu)) mainLayout.addWidget(adv, 1, column) column += 1 for i in range(column): mainLayout.setColumnStretch(i, 1) tray = QHBoxLayout() tray.addWidget(Clock()) tray.addWidget(SystemStatus(controller)) mainLayout.addLayout(tray, 1, column) mainLayout.setRowStretch(0, 8) mainLayout.setRowStretch(1, 0) outer.setLayout(mainLayout) self.setCentralWidget(outer) self.pnd = PowerNotificationDialog(self) self.pnd.accepted.connect(self.hidePowerDialog)
class NotificationTab(): """ui class for new notification tab""" global logger def __init__(self): ##### logger.info('Inside PurchaseSchedule') self.notificationTab_tab_4 = QWidget() self.notificationTab_tab_4.setObjectName("notificationTab_tab_4") self.gridLayout_19 = QGridLayout(self.notificationTab_tab_4) self.gridLayout_19.setObjectName("gridLayout_19") ## self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.title_label = QLabel(self.notificationTab_tab_4) self.title_label.setObjectName("title_label") self.horizontalLayout.addWidget(self.title_label) self.gridLayout_19.addLayout(self.horizontalLayout, 0, 0, 1, 1) ## self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.id_label = QLabel(self.notificationTab_tab_4) self.id_label.setObjectName("id_label") self.horizontalLayout_6.addWidget(self.id_label) self.id_line = QLineEdit(self.notificationTab_tab_4) self.id_line.setObjectName("id_line") self.horizontalLayout_6.addWidget(self.id_line) self.notification_schedule_fromdate_label = QLabel( self.notificationTab_tab_4) self.notification_schedule_fromdate_label.setObjectName( "notification_schedule_fromdate_label") self.horizontalLayout_6.addWidget( self.notification_schedule_fromdate_label) self.notification_schedule_fromdate_dateedit = QDateEdit( self.notificationTab_tab_4) self.notification_schedule_fromdate_dateedit.setMaximumDate( QDate.currentDate()) self.notification_schedule_fromdate_dateedit.setDate( QDate.currentDate()) self.notification_schedule_fromdate_dateedit.setCalendarPopup(True) self.notification_schedule_fromdate_dateedit.setObjectName( "notification_schedule_fromdate_dateedit") self.horizontalLayout_6.addWidget( self.notification_schedule_fromdate_dateedit) self.notification_schedule_todate_label = QLabel( self.notificationTab_tab_4) self.notification_schedule_todate_label.setObjectName( "notification_schedule_todate_label") self.horizontalLayout_6.addWidget( self.notification_schedule_todate_label) self.notification_schedule_todate_dateedit = QDateEdit( self.notificationTab_tab_4) self.notification_schedule_todate_dateedit.setMaximumDate( QDate.currentDate()) self.notification_schedule_todate_dateedit.setDate(QDate.currentDate()) self.notification_schedule_todate_dateedit.setCalendarPopup(True) self.notification_schedule_todate_dateedit.setObjectName( "notification_schedule_todate_dateedit") self.horizontalLayout_6.addWidget( self.notification_schedule_todate_dateedit) self.type_label = QLabel(self.notificationTab_tab_4) self.type_label.setObjectName("type_label") self.horizontalLayout_6.addWidget(self.type_label) self.notification_states = QComboBox(self.notificationTab_tab_4) self.notification_states.setObjectName("notification_states") self.horizontalLayout_6.addWidget(self.notification_states) self.batch_label = QLabel(self.notificationTab_tab_4) self.batch_label.setObjectName("batch_label") self.horizontalLayout_6.addWidget(self.batch_label) self.notification_results = QComboBox(self.notificationTab_tab_4) self.notification_results.setObjectName("notification_results") self.horizontalLayout_6.addWidget(self.notification_results) self.gridLayout_19.addLayout(self.horizontalLayout_6, 1, 0, 1, 1) self.gridLayout_8 = QGridLayout() self.gridLayout_8.setObjectName("gridLayout_8") self.notification_schedule_table = QTableWidget( self.notificationTab_tab_4) self.notification_schedule_table.setObjectName( "notification_schedule_table") self.notification_schedule_table.setColumnCount(5) self.notification_schedule_table.setRowCount(0) self.notification_schedule_table.setWordWrap(True) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(4, item) self.notification_schedule_table.horizontalHeader( ).setCascadingSectionResizes(True) self.notification_schedule_table.horizontalHeader( ).setStretchLastSection(True) self.notification_schedule_table.verticalHeader().setVisible(False) self.notification_schedule_table.verticalHeader( ).setCascadingSectionResizes(True) self.notification_schedule_table.verticalHeader( ).setStretchLastSection(False) self.gridLayout_8.addWidget(self.notification_schedule_table, 0, 0, 1, 5) self.notification_search_button = QPushButton( self.notificationTab_tab_4) self.notification_search_button.setObjectName( "notification_search_button") self.gridLayout_8.addWidget(self.notification_search_button, 1, 0, 1, 1) spacerItem10 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_8.addItem(spacerItem10, 1, 2, 1, 1) self.notification_reset_button = QPushButton( self.notificationTab_tab_4) self.notification_reset_button.setObjectName( "notification_reset_button") self.gridLayout_8.addWidget(self.notification_reset_button, 1, 3, 1, 1) self.notification_load_more_button = QPushButton( self.notificationTab_tab_4) self.notification_load_more_button.setObjectName( "notification_load_more_button") self.gridLayout_8.addWidget(self.notification_load_more_button, 1, 4, 1, 1) self.gridLayout_19.addLayout(self.gridLayout_8, 2, 0, 1, 1) ###retranslate self.title_label.setText( QApplication.translate( "MainWindow", "<html><head/><body><p align=\"center\">" "<span style=\" font-weight:600;font-size:20px\">" "<u>All Notifications</u></span></p></body></html>", None, QApplication.UnicodeUTF8)) self.id_label.setText( QApplication.translate("MainWindow", "Message Id", None, QApplication.UnicodeUTF8)) self.notification_schedule_fromdate_label.setText( QApplication.translate("MainWindow", "From Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_fromdate_dateedit.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.notification_schedule_todate_label.setText( QApplication.translate("MainWindow", "To Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_todate_dateedit.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.type_label.setText( QApplication.translate("MainWindow", "Type", None, QApplication.UnicodeUTF8)) self.batch_label.setText( QApplication.translate("MainWindow", "Number of Notifications", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(0).setText( QApplication.translate("MainWindow", "Message Id", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(1).setText( QApplication.translate("MainWindow", "Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(2).setText( QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(3).setText( QApplication.translate("MainWindow", "Message", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(4).setText( QApplication.translate("MainWindow", "State", None, QApplication.UnicodeUTF8)) self.notification_search_button.setText( QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.notification_reset_button.setText( QApplication.translate("MainWindow", "Reset All", None, QApplication.UnicodeUTF8)) self.notification_load_more_button.setText( QApplication.translate("MainWindow", "Load More", None, QApplication.UnicodeUTF8)) ##signals and slotts && other stuffs self.scheduletable_count = 0 self.addtable_count = 0 # self.mainwindow = Ui_MainWindow # just for the ease of finding the attributes in pycharm self.notification_schedule_table.setEditTriggers( QAbstractItemView.NoEditTriggers) self.batch_number = None self.notification_results.addItems([str(i) for i in range(1, 50, 5)]) self.notification_states.addItems(['All', 'New', 'To Do', 'Done']) self.message = Messaging() self.notification_load_more_button.clicked.connect(self.load_more) self.notification_search_button.clicked.connect(self.search_messages) self.notification_reset_button.clicked.connect(self.reset_all) self.notificationTab_tab_4.setFocusPolicy(Qt.StrongFocus) self.notificationTab_tab_4.focusInEvent = self.load_rows # self.assign_shortcuts() # def assign_shortcuts(self): # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_search']), # self.notificationTab_tab_4, self.search_messages) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_additem']), # self.notificationTab_tab_4, self.add_new_blank_rows) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_print']), # self.notificationTab_tab_4, self.commit_and_print) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_today']), # self.notificationTab_tab_4, lambda: self.load_messages('today')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_tommorow']), # self.notificationTab_tab_4, lambda: self.load_messages('tomorrow')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thismonth']), # self.notificationTab_tab_4, lambda: self.load_messages('month')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thisweek']), # self.notificationTab_tab_4, lambda: self.load_messages('week')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_clear']), # self.notificationTab_tab_4, self.clear_table) def add_messages(self, *args): """ Populates the Schedules when we load the tab """ table = self.notification_schedule_table if args: if args[0] != 'new': table.clearContents() table.setRowCount(0) table.setRowCount(len(args)) for i, j in enumerate(args): item = QTableWidgetItem(j['msg_id']) table.setItem(i, 0, item) item = QTableWidgetItem(j['date']) table.setItem(i, 1, item) item = QTableWidgetItem( 'Name:{}\nDesignation:{}\nAddress:{}'.format( j['name'], j['designation'], j['address'])) table.setItem(i, 2, item) item = QTableWidgetItem( 'Message Type:{}\nMessage:{}'.format( j['msg_type'].title(), j['msg_body'])) table.setItem(i, 3, item) states = QComboBox() self.populate_states(states, j['msg_state'].title()) states.currentIndexChanged.connect( lambda index, row=i: self.changed_state(row, index)) table.setCellWidget(i, 4, states) elif args[0] == 'new': initial = table.rowCount() row = table.rowCount() + len(args[1]) table.setRowCount(row) forward_range = range(initial, row) for i, j in zip(forward_range, args[1]): item = QTableWidgetItem(j['msg_id']) table.setItem(i, 0, item) item = QTableWidgetItem(j['date']) table.setItem(i, 1, item) item = QTableWidgetItem( 'Name:{}\nDesignation:{}\nAddress:{}'.format( j['name'], j['designation'], j['address'])) table.setItem(i, 2, item) item = QTableWidgetItem( 'Message Type:{}\nMessage:{}'.format( j['msg_type'].title(), j['msg_body'])) table.setItem(i, 3, item) states = QComboBox() self.populate_states(states, j['msg_state'].title()) states.currentIndexChanged.connect( lambda index, row=i: self.changed_state(row, index)) table.setCellWidget(i, 4, states) table.setColumnWidth(0, (table.width() * 0.5) / 5) table.setColumnWidth(1, (table.width() * 0.5) / 5) table.setColumnWidth(2, table.width() / 5) table.setColumnWidth(3, (table.width() * 2) / 5) self.notification_schedule_table.resizeRowsToContents() def populate_states(self, combo, state): """ fills the supplier list for each item line :param combo: the combo box of suppliers :return:none """ combo.setStyleSheet("QAbstractItemView{" "background: #4B77BE;" "}") combo.addItems(['New', 'To Do', 'Done']) index = combo.findText(state) combo.setCurrentIndex(index) def changed_state(self, row, index): """ fill the item combo box :param combo: the combobox object :return: none """ table = self.notification_schedule_table data = {} data['message_id'] = table.item(row, 0).text() data['msg_state'] = table.cellWidget(row, 4).currentText() msg = QMessageBox.information( QMessageBox(), 'Alert!!', 'Do you want to change the status of the Message??', QMessageBox.Yes | QMessageBox.No) if msg == QMessageBox.Yes: report = self.message.update_message(data) if report: _ = QMessageBox.information(QMessageBox(), 'Success!!', 'The Message was updated', QMessageBox.Yes | QMessageBox.No) else: _ = QMessageBox.critical(QMessageBox(), 'Error!!', 'The Message was not updated', QMessageBox.Yes | QMessageBox.No) def search_messages(self): """ Searches for messages when search button is pressed """ logger.info('Notifications searching messages initiated') from_date = self.notification_schedule_fromdate_dateedit.text() to_date = self.notification_schedule_todate_dateedit.text() limit = self.notification_results.currentText() msg_id = self.id_line.text() msg_state = self.notification_states.currentText() dataobj = self.message.load_message(limit=limit, from_date=from_date, to_date=to_date, msg_id=msg_id, msg_state=msg_state) if dataobj: self.add_messages(*dataobj) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_more(self): """ Searches for messages when search button is pressed """ logger.info('Notifications searching messages initiated') from_date = self.notification_schedule_fromdate_dateedit.text() to_date = self.notification_schedule_todate_dateedit.text() limit = self.notification_results.currentText() msg_id = self.id_line.text() msg_state = self.notification_states.currentText() offset = self.notification_schedule_table.rowCount() dataobj = self.message.load_message(limit=limit, from_date=from_date, to_date=to_date, msg_id=msg_id, msg_state=msg_state, offset=offset) if dataobj: self.add_messages('new', dataobj) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_single_message(self, msg_id): # api """method to load a single message""" self.reset_all() dataobj = self.message.load_message(msg_id=msg_id) if dataobj: self.add_messages('new', dataobj) self.id_line.setText(str(msg_id)) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_rows(self, event): """ :return:loads the rows """ self.add_messages() def reset_all(self): """ :return: resets the the data in the search text """ try: self.id_line.clear() self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) except Exception as _: if settings.level == 10: logger.exception('raised exception') return False
def initUI(self): layout = QGridLayout() self.setLayout(layout) self.btnUp = CameraButton(CameraMove.Up) layout.addWidget(self.btnUp, 0, 1, 2, 1) self.btnUp.pressed.connect(self.move) self.btnUp.released.connect(self.stop) self.btnUp.setIcon(QIcon("icons/go-up.svg")) self.btnLeft = CameraButton(CameraMove.Left) layout.addWidget(self.btnLeft, 1, 0, 2, 1) self.btnLeft.pressed.connect(self.move) self.btnLeft.released.connect(self.stop) self.btnLeft.setIcon(QIcon("icons/go-previous.svg")) self.btnDown = CameraButton(CameraMove.Down) layout.addWidget(self.btnDown, 2, 1, 2, 1) self.btnDown.pressed.connect(self.move) self.btnDown.released.connect(self.stop) self.btnDown.setIcon(QIcon("icons/go-down.svg")) self.btnRight = CameraButton(CameraMove.Right) layout.addWidget(self.btnRight, 1, 2, 2, 1) self.btnRight.pressed.connect(self.move) self.btnRight.released.connect(self.stop) self.btnRight.setIcon(QIcon("icons/go-next.svg")) zoomInOut = PlusMinusButtons("Zoom", CameraZoom.Tele, CameraZoom.Wide) zoomInOut.connectPressed(self.zoom) zoomInOut.connectReleased(self.stopZoom) layout.addWidget(zoomInOut, 0, 3, 4, 1) focus = PlusMinusAutoButtons("Focus", CameraFocus.Far, CameraFocus.Near, CameraFocus.Auto) focus.connectPressed(self.focus) focus.connectReleased(self.stopFocus) focus.autoButton.clicked.connect(self.focus) layout.addWidget(focus, 0, 4, 4, 1) brightness = PlusMinusButtons("Brightness", True, False) brightness.connectClicked(self.exposure) layout.addWidget(brightness, 0, 5, 4, 1) presets = QGridLayout() presets.setRowStretch(0, 2) presets.setRowStretch(1, 1) self.presetGroup = QButtonGroup() for i in range(0, 6): btnPresetRecall = CameraButton(i) presets.addWidget(btnPresetRecall, 0, i, 1, 1) btnPresetRecall.setText(str(i + 1)) btnPresetRecall.clicked.connect(self.recallPreset) btnPresetRecall.setCheckable(True) self.presetGroup.addButton(btnPresetRecall, i) btnPresetSet = CameraButton(i) presets.addWidget(btnPresetSet, 1, i, 1, 1) btnPresetSet.setText("Set") btnPresetSet.clicked.connect(self.storePreset) layout.addLayout(presets, 4, 0, 3, 6)
class EditorWindow(QMainWindow): """initialize editor""" def __init__(self, tixi, xmlFilename, cpacs_scheme=Config.path_cpacs_21_schema): super(EditorWindow, self).__init__() self.cur_file_path = "" self.cur_schema_path = "" self.setupEditor() self.setupButtonMenu() self.setupSearchBox() self.setupStatusbar() self.setupMenubar() self.setupNumbar() self.popUpWidget = None self.flag_layout = False self.hbox = QHBoxLayout() self.hbox.setSpacing(0) self.hbox.setContentsMargins(0,0,0,0) self.hbox.addWidget(self.number_bar) self.hbox.addWidget(self.editor) self.layout = QGridLayout() self.layout.addWidget(self.searchbox, 0, 0, 1, 4) self.layout.addWidget(self.button1, 0, 4, 1, 1) self.layout.addWidget(self.button2, 0, 5, 1, 1) self.layout.addLayout(self.hbox, 2, 0, 1, 8) self.layout.addWidget(self.fontsizeSpinBox, 0, 6, 1, 1) self.layout.addWidget(self.label1, 0, 7, 1, 1) self.window = QWidget() self.window.setLayout(self.layout) self.setWindowTitle('Simple XML editor') self.setCentralWidget(self.window) self.resize(800, 800) self.show() self.tixi = tixi self.loadFile(xmlFilename, cpacs_scheme) ''' loads cpacs file and validates it against the cpacs_schema @param xmlFilename: input file @param cpacs_scheme: validation scheme ''' def loadFile(self, xmlFilename=None, cpacs_scheme=Config.path_cpacs_21_schema): if xmlFilename and cpacs_scheme : try: self.tixi.open(xmlFilename) #self.tixi.openDocument(xmlFilename) #self.tixi.schemaValidateFromFile(cpacs_scheme) self.editor.setPlainText(self.tixi.exportDocumentAsString()) self.cur_file_path = xmlFilename self.cur_schema_path = cpacs_scheme except TixiException as e: self.statusBar().showMessage('CPACS ERROR: ' + e.error) ''' update the dictionary by the cpacs scheme @param path_dict: path to directory @param path_scheme: path to cpacs_scheme ''' def updatedictionary(self, path_dict=Config.path_code_completion_dict, path_scheme=Config.path_cpacs_21_schema): found = False olddict = open(path_dict) scheme_file = open(path_scheme, 'r') with open(path_dict, "a") as newdict : for line in scheme_file : word = re.search("(?<=\<xsd:complexType name=\").*(?=\"\>)", line) if word != None : for tmp in olddict : if tmp == word.group(0) +"\n" : found = True break if(not found) : newdict.write(word.group(0)+"\n") olddict.seek(0) found = False olddict.close() newdict.close() scheme_file.close() ''' validate xml file and write result to statusBar ''' def validate(self): try: etree.fromstring(str(self.editor.toPlainText())) self.statusBar().showMessage("Valid XML") except etree.XMLSyntaxError as e: if e.error_log.last_error is not None: msg = e.error_log.last_error.message line = e.error_log.last_error.line col = e.error_log.last_error.column self.statusBar().showMessage("Invalid XML: Line %s, Col %s: %s"%(line,col,msg)) except: self.statusBar().showMessage("Invalid XML: Unknown error") ''' close and cleanup tixi ''' def __del__(self): pass #self.tixi.close() #self.tixi.cleanup() ''' set and connect the search buttons ''' def setupButtonMenu(self): self.button1 = QPushButton("previous" ) self.button2 = QPushButton("next" ) self.label1 = QLabel("font") self.fontsizeSpinBox = QSpinBox() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() self.button1.clicked.connect(self.fire_search_backward) self.button2.clicked.connect(self.fire_search_foreward) self.fontsizeSpinBox.setRange(4, 30) self.fontsizeSpinBox.setSingleStep(1) self.fontsizeSpinBox.setSuffix('pt') self.fontsizeSpinBox.setValue(10) self.fontsizeSpinBox.valueChanged.connect(self.setfontsize) def setfontsize(self, value): self.font.setPointSize(value) self.editor.setFont(self.font) def setupEditor(self): self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(10) self.editor = EditorCodeCompletion(Config().path_code_completion_dict) self.editor.setFont(self.font) self.editor.setTabStopWidth(20) self.editor.setAcceptRichText(False) self.editor.setLineWrapMode(QTextEdit.NoWrap) self.editor.textChanged.connect(self.validate) self.highlighter = Highlighter(self.editor.document()) def setupNumbar(self): self.number_bar = NumberBar() self.number_bar.setTextEdit(self.getStates()) self.editor.cursorPositionChanged.connect(self.fireUpdateNumbar) self.connect(self.editor.verticalScrollBar(), SIGNAL("valueChanged(int)"), self.fireUpdateNumbar) #self.editor.verticalScrollBar.valueChanged.connect(self.fireUpdateNumbar) def setupStatusbar(self): self.lineNumber = -1 self.colNumber = -1 self.m_statusRight = QLabel("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber), self) self.statusBar().addPermanentWidget(self.m_statusRight, 0) def setupSearchBox(self): self.searchbox = SearchField() self.searchbox.hide() def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu) #self.editor.connect(self.editor, SIGNAL( "customContextMenuRequested(QPoint)" ), self.showMenu ) def showMenu( self, pos ): """ Show a context menu for the active layer in the legend """ menu = self.editor.createStandardContextMenu() menu.addAction(self.xpathAction) menu.exec_(QtCore.QPoint( self.mapToGlobal( pos ).x() + 5, self.mapToGlobal( pos ).y() )) def fireUpdateNumbar(self): self.updateLineNumber() self.number_bar.update() def dummyFuction(self): print ("not implemented yet") def getStates(self): self.stats = { "searchbox":self.searchbox, "editor":self.editor} return self.stats ''' find previous button ''' def fire_search_backward(self): self.editor.find(self.searchbox.text(), QTextDocument.FindBackward) self.searchbox.setFocus() ''' find next button ''' def fire_search_foreward(self): #print self.tixi.getNumberOfChilds('/cpacs/vehicles/aircraft/model[@uID="Aircraft1"]/wings/wing[@uID="Aircraft1_Wing1"]/transformation[@uID="Aircraft1_Wing1_Transf"]/scaling[@uID="Aircraft1_Wing1_Transf_Sca"]/z') searchList = list(filter(lambda a : a!='', self.searchbox.text().split('/'))) if len(searchList) == 1 : if self.editor.find(searchList[0]) : pass elif not self.editor.find(searchList[0], QTextDocument.FindBackward): QMessageBox.about(self, "error", "String %s not found" % (searchList[0])) else : self.editor.moveCursor(QTextCursor.Start) self.editor.find(searchList[0]) else : self.searchXPath(self.searchbox.text(), searchList) self.searchbox.setFocus() # test # /cpacs/vehicles/aircraft/model/wings/wing/sections/section def searchXPath(self, path, searchList): try: if self.tixi.xPathEvaluateNodeNumber(path) > 1 : QMessageBox.about(self, "error", "XPath %s not unique" % path) return self.editor.moveCursor(QTextCursor.Start) found = True # search index snd loop j = 0 # search backwards for uid for i in range(len(searchList)-1, -1, -1) : if '[' in searchList[i] : # get value in brackets : [x] --> x uid = re.search(r'\[(.*)\]', searchList[i]).group(1) uid = self.__transToSearchUid(searchList[:i+1], uid) found = self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while found and j < len(searchList) : found = self.editor.find('<'+searchList[j]) j += 1 if not found : QMessageBox.about(self, "error", "XPath %s not found" % path) except TixiException : QMessageBox.about(self, "error", "XPath %s not found" % path) def __transToSearchUid(self, path_list, uid): try: int(uid) path = "" for p in path_list : path = path + '/' + p return self.tixi.getTextAttribute(path , 'uID') except ValueError: return uid.replace('@', '') def getCursorXPath(self): start_pos = self.editor.textCursor().position() tag , tag_pos , isCursorInTag = self.getTagNameAtCursor() _,xpath_idx, xpath_uid = self.__findXPath_rec('/cpacs', '/cpacs' , tag, tag_pos) if not isCursorInTag: xpath_idx = self.__strRemoveReverseToChar(xpath_idx, '/') xpath_uid = self.__strRemoveReverseToChar(xpath_uid, '/') self.__setCursorToPostion(start_pos) self.__startXPathPopUp(xpath_idx, xpath_uid) def getTagNameAtCursor(self): ''' @return: name of tag , position of tag , cursor is btw open and closing tag ''' self.editor.find('<', QTextDocument.FindBackward) isClosingTag , fst_tag = self.__getTagName() pos = self.editor.textCursor().position() if isClosingTag : # find open tag of this closing tag self.editor.find('<'+fst_tag, QTextDocument.FindBackward) pos = self.editor.textCursor().position() return fst_tag , pos , False else: return fst_tag , pos , True def __getTagName(self): tc = self.editor.textCursor() tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = False if "</" in tx : # select next word tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = True return isClosingTag , "" if "<" in tx else tx def __findXPath_rec(self, xpath_idx, xpath_uid, search, pos): nodes = self.__getChildNodesIdxTuple(xpath_idx) for (node, idx) in nodes: if node != '#text' : new_xpath_idx, new_xpath_uid = self.__createNewXPath(xpath_idx, xpath_uid, node, idx) if search == node and self.isNodeAtSearchedTagPosition(new_xpath_uid, pos) : print ("gefunden" , new_xpath_idx) return True, new_xpath_idx , new_xpath_uid else: flag , res_idx, res_uid = self.__findXPath_rec(new_xpath_idx, new_xpath_uid, search, pos) if flag : return True, res_idx, res_uid return False , xpath_idx , xpath_uid def __getChildNodesIdxTuple(self, xpath): n = self.tixi.getNumberOfChilds(xpath) + 1 node_list = list(map(lambda i : self.tixi.getChildNodeName(xpath, i), range(1,n))) res = [] for j in range(len(node_list)) : cnt = 1 for k in range(j): if node_list[k] == node_list[j] : cnt = cnt + 1 res.append((node_list[j],cnt)) return res def __createNewXPath(self, xpath_idx, xpath_uid, node, idx): path_idx = xpath_idx + '/' + node path_uid = xpath_uid + '/' + node try : uID = self.tixi.getTextAttribute(path_idx + '[' + str(idx) + ']', 'uID') path_idx = path_idx + '[' + str(idx) + ']' path_uid = path_uid+'[@uID="' + uID + '"]' except TixiException: pass # e.error == 'ATTRIBUTE_NOT_FOUND return path_idx , path_uid def isNodeAtSearchedTagPosition(self, xpath, pos): ''' @param xpath: xpath with uids (doesn't work with indices) @param param: ''' self.editor.moveCursor(QTextCursor.Start) # split string at / and remove all empty strings l = list(filter(lambda x : x != '' , xpath.split('/'))) # search index snd loop j = 0 # search backwards for uid for i in range(len(l)-1, -1, -1) : if '[' in l[i] : # get value in brackets : [x] --> x uid = re.search(r'\[@(.*)\]', l[i]).group(1) self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while j < len(l) : self.editor.find('<'+l[j]) j += 1 return pos <= self.editor.textCursor().position() def __setCursorToPostion(self, pos): tc = self.editor.textCursor() tc.setPosition(pos) self.editor.setTextCursor(tc) def __startXPathPopUp(self, xpath_idx, xpath_uid): self.popUpWidget = XPathDialog(xpath_idx, xpath_uid) self.setEnabled(False) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def updateLineNumber(self): ''' sets the line and column number ''' self.lineNumber = self.editor.textCursor().blockNumber() + 1 self.colNumber = self.editor.textCursor().columnNumber() + 1 self.m_statusRight.setText("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber)) def highlightCurrentLine(self) : ''' highlight line under cursor ''' extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(255, 250, 205) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.editor.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.editor.setExtraSelections(extraSelections) self.editor.setFocus() #TODO: implemnt def fireUpdate(self): print ('dummy function - update the model') text_file = open(Config.path_cpacs_tmp_file, "w") text_file.write(self.editor.toPlainText()) text_file.close() #self.tixi.saveDocument(Config.path_cpacs_tmp_file) # '../cpacs_files/temp.xml' def fireRevert(self): ''' reloads cpacs file if not updated yet ''' if(self.cur_file_path and self.cur_schema_path) : self.loadFile(self.cur_file_path, self.cur_schema_path) else : QMessageBox.about(self, "error", "CPACS-File or Validation-Schema not available") def fireSwitchLayout(self): ''' function to show or hide line numbers ''' if(self.flag_layout) : self.number_bar.flag_show_numbers = True self.update() else : self.number_bar.flag_show_numbers = False self.update() self.flag_layout = not self.flag_layout def fireNewAction(self): ''' opens new file input form ''' self.setEnabled(False) self.popUpWidget = NewFileDialog() self.popUpWidget.buttonBox.accepted.connect(self.__createNewCpacsFile) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def fireToolX(self): self.popUpWidget = ToolX("X-Tool", self.tixi) self.setEnabled(False) self.popUpWidget.buttonBox.accepted.connect(self.__resetPopUpWidget) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) # closeAct for pressing X to close window self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def __createNewCpacsFile(self): ''' closes all documents and creates new empty cpacs temporary file ''' idict = self.popUpWidget.fire_submitInput() self.tixi.closeAllDocuments() self.tixi.create('cpacs') self.tixi.addCpacsHeader(idict['name'], idict['creator'], idict['version'], idict['description'], idict['cpacsVersion']) self.tixi.saveDocument(Config.path_cpacs_tmp_file) self.loadFile(Config.path_cpacs_tmp_file) self.__resetPopUpWidget() def __resetPopUpWidget(self): self.popUpWidget.close() self.popUpWidget = None self.setEnabled(True) def fireComment(self): ''' inserts open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() tc.beginEditBlock() tc.setPosition(self.editor.textCursor().selectionStart()) tc.insertText("<!--") tc.setPosition(self.editor.textCursor().selectionEnd()) tc.insertText("-->") tc.endEditBlock() def fireUnComment(self): ''' removes open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() selectTxt = tc.selectedText() if selectTxt.find('<!--') != -1 : if selectTxt.rfind('-->') != -1 : selectTxt = selectTxt.replace('<!--', '', 1) selectTxt = self.__rreplace(selectTxt, '-->' , '', 1) tc.insertText(selectTxt) else: QMessageBox.about(self, "error", "no open tag (%s) in selection" % ('-->')) else: QMessageBox.about(self, "error", "no close tag (%s) in selection" % ('<!--')) def fireSearchView(self): ''' show and hide searchbox and buttons ''' if self.searchbox.isFocused() : self.searchbox.hide() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() else : self.searchbox.show() self.button1.show() self.button2.show() self.label1.show() self.fontsizeSpinBox.show() self.searchbox.setFocus() def keyPressEvent(self,event): ''' handle for searching strings by pressing enter key ''' if self.searchbox.isFocused() and event.key() == Qt.Key_Return : self.fire_search_foreward() # ====================================================================================================================== # utilities # ====================================================================================================================== def __strRemoveReverseToChar(self, s, c): return self.__rm_rec(s, c) def __rm_rec(self, s, c): if s == "" : return "" elif s[-1] == c : return s[:-1] else : return self.__rm_rec(s[:-1], c) def __rreplace(self, s, old, new, occurrence): ''' reverse string replace function @param s: source string @param old: char to be replaced @param new: new char @param occurrence: only the given count occurrences are replaced. ''' li = s.rsplit(old, occurrence) return new.join(li)
def initUI(self): grp = QGroupBox('Model') grplay = QGridLayout() name = QLineEdit() name.setText(self.mdl.name) name.textChanged.connect(self.name_changed) self.controls['name'] = name grplay.addWidget(QLabel('Name'), 0, 0) grplay.addWidget(name, 0, 1) parent = QLineEdit() parent.setText(self.mdl.parent_name) self.controls['parent'] = parent grplay.addWidget(QLabel('Parent'), 0, 2) grplay.addWidget(parent, 0, 3) type_ = QComboBox() type_.addItems(self.types) type_.setCurrentIndex(self.types2[self.mdl.model_type]) self.controls['type'] = type_ grplay.addWidget(QLabel('Type'), 1, 0) grplay.addWidget(type_, 1, 1) vis = QCheckBox() if self.mdl.vis: vis.toggle() self.controls['vis'] = vis grplay.addWidget(QLabel('Hidden'), 1, 2) grplay.addWidget(vis, 1, 3) buttonlay = QHBoxLayout() collprim = QPushButton('Collision Primitive') buttonlay.addWidget(collprim) collprim.clicked.connect(self.edit_collprim) deformers = QPushButton('Deformers') deformers.clicked.connect(self.edit_deformers) buttonlay.addWidget(deformers) bbox_btn = QPushButton('Bounding Box') bbox_btn.clicked.connect(self.edit_bbox) trans = QPushButton('Transform') trans.clicked.connect(self.edit_tran) buttonlay.addWidget(bbox_btn) buttonlay.addWidget(trans) buttonlay2 = QHBoxLayout() validate = QPushButton('Validate') validate.clicked.connect(self.validate) uvs = QPushButton('UVs') uvs.clicked.connect(self.show_uvs) buttonlay2.addWidget(validate) buttonlay2.addWidget(uvs) buttonlay2.addStretch() grplay.addLayout(buttonlay, 2, 0, 1, 4) grplay.addLayout(buttonlay2, 3, 0, 1, 4) grp.setLayout(grplay) geogrp = QGroupBox('Geometry') geolay = QHBoxLayout() self.geometries = QListWidget() self.geometries.addItems(['{0} - {1}'.format(ind, geo.classname) for ind, geo in enumerate(self.mdl.segments)]) geolay.addStretch() geolay.addWidget(self.geometries) edit_geo = QPushButton('Edit') edit_geo.clicked.connect(self.edit_geo) geolay.addWidget(edit_geo) geogrp.setLayout(geolay) btns = QHBoxLayout() save = QPushButton('Save') save.clicked.connect(self.save) cancel = QPushButton('Cancel') cancel.clicked.connect(self.close) self.status = QLabel('Model Edit Mode') btns.addWidget(self.status) btns.addStretch() btns.addWidget(save) btns.addWidget(cancel) mainlay = QVBoxLayout() mainlay.addWidget(grp) mainlay.addWidget(geogrp) mainlay.addLayout(btns) self.setLayout(mainlay) self.setGeometry(340, 340, 400, 200) self.setWindowTitle('MSH Suite - {0}'.format(self.mdl.name)) self.show()
class ViewSearch(QWidget): """ Search widget """ def __init__(self, p_def): """ :param p_def: {id, name, type} :return: """ QWidget.__init__(self) # 控件定义 self.__fields_def = p_def # 每行默认控件数 self.__columns = 4 # 控件字典 self.__inputs = {} # 布局 self.__layout_srh = QGridLayout() self.setLayout(self.__layout_srh) self.setStyleSheet(get_theme("Input")) def set_col_num(self, p_num): """ 设置每行控件数 :param p_num: :type p_num: int :return: """ self.__columns = p_num def create(self): items = [] for t_def in self.__fields_def: if not t_def['SEARCH']: continue # 控件标签 _label = QLabel(t_def['NAME'] + ":") # 控件 _def = dict(TYPE=t_def["TYPE"], SOURCE="SEARCH", FLAG=t_def["ID"]) self.__inputs[t_def['ID']] = create_editor(self, _def) # 控件布局 _layout = QHBoxLayout() _layout.addWidget(_label) _layout.addWidget(self.__inputs[t_def['ID']]) items.append(_layout) # 控件及其 label 加入主布局 for _index in range(len(items)): _row = _index % self.__columns _column = _index / self.__columns self.__layout_srh.addLayout(items[_index], _column, _row) def get_cond(self): """ 获取 条件 :return: {name:value, ...} """ return {_inp: self.__inputs[_inp].get_data() for _inp in self.__inputs}
class HygieneReportPop(QDialog): """ The Report Form Handler """ def __init__(self, parent=None, code=None, table=None): super(HygieneReportPop, self).__init__() self.setup_pop() # do not change the order of these two function self.code = code self.parent_object = parent self.image_data = None self.process_override( table=table) # do not change the order of these two function if not code: self.update_button.setHidden(True) self.delete_button.setHidden(True) self.calculate_code() else: self.create_button.setHidden(True) self.update_data() def process_override(self, table): """ Function that assigns the table and tryton backend handler objects based on the tables :param table: the table name """ try: if table == 'pest_table': self.backend_handle = self.parent_object.pest self.table = self.parent_object.report_hyginepest_table elif table == 'water_table': self.backend_handle = self.parent_object.water self.table = self.parent_object.report_hyginewater_table elif table == 'health_table': self.backend_handle = self.parent_object.health self.table = self.parent_object.report_health_table except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def setup_pop(self): """ sets up the form. """ self.grid_layout = QGridLayout(self) self.label_1 = QLabel(self) self.grid_layout.addWidget(self.label_1, 0, 0, 1, 1) self.code_line = QLineEdit(self) self.code_line.setValidator(QIntValidator(0, 99999)) self.grid_layout.addWidget(self.code_line, 0, 1, 1, 1) self.label_2 = QLabel(self) self.grid_layout.addWidget(self.label_2, 1, 0, 1, 1) self.date_line = QDateEdit(self) self.date_line.setCalendarPopup(True) self.grid_layout.addWidget(self.date_line, 1, 1, 1, 1) self.label_3 = QLabel(self) self.grid_layout.addWidget(self.label_3, 2, 0, 1, 1) self.organization_line = QLineEdit(self) self.grid_layout.addWidget(self.organization_line, 2, 1, 1, 1) self.label_4 = QLabel(self) self.grid_layout.addWidget(self.label_4, 3, 0, 1, 1) self.test_line = QLineEdit(self) self.grid_layout.addWidget(self.test_line, 3, 1, 1, 1) self.label_5 = QLabel(self) self.grid_layout.addWidget(self.label_5, 4, 0, 1, 1) self.description_line = QLineEdit(self) self.grid_layout.addWidget(self.description_line, 4, 1, 1, 1) self.image_label = QLabel(self) self.pixmap = QPixmap(':/images/upload.png') # self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation) #not used self.image_label.setPixmap(self.pixmap) self.image_label.setScaledContents(True) self.grid_layout.addWidget(self.image_label, 0, 2, 5, 2) self.horizontal = QHBoxLayout() self.delete_button = QPushButton(self) self.horizontal.addWidget(self.delete_button) self.create_button = QPushButton(self) self.horizontal.addWidget(self.create_button) self.update_button = QPushButton(self) self.horizontal.addWidget(self.update_button) self.upload_button = QPushButton(self) self.horizontal.addWidget(self.upload_button) self.grid_layout.addLayout(self.horizontal, 5, 0, 1, 4) ### retanslate self.label_1.setText( QApplication.translate("MainWindow", "Code", None, QApplication.UnicodeUTF8)) self.label_2.setText( QApplication.translate("MainWindow", "Date", None, QApplication.UnicodeUTF8)) self.date_line.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.label_3.setText( QApplication.translate("MainWindow", "Organization Name", None, QApplication.UnicodeUTF8)) self.label_4.setText( QApplication.translate("MainWindow", "Test", None, QApplication.UnicodeUTF8)) self.label_5.setText( QApplication.translate("MainWindow", "Description", None, QApplication.UnicodeUTF8)) self.delete_button.setText( QApplication.translate("MainWindow", "Delete", None, QApplication.UnicodeUTF8)) self.create_button.setText( QApplication.translate("MainWindow", "Create", None, QApplication.UnicodeUTF8)) self.update_button.setText( QApplication.translate("MainWindow", "Update", None, QApplication.UnicodeUTF8)) self.upload_button.setText( QApplication.translate("MainWindow", "Upload", None, QApplication.UnicodeUTF8)) self.create_button.clicked.connect(self.create_report) self.upload_button.clicked.connect(self.open_file) self.update_button.clicked.connect(self.update_report) self.delete_button.clicked.connect(self.delete_report) self.image_label.mouseReleaseEvent = self.image_viewer def update_data(self): """ Updates the data in the form """ try: data = self.backend_handle.read_report(code=int(self.code)) if data: if data[0]: data = data[1] self.code_line.setText(data['code']) self.code_line.setDisabled(True) self.date_line.setDate(data['date']) self.organization_line.setText(data['organization']) self.test_line.setText(data['test']) self.description_line.setText(data['description']) self.image_data = str(data['report']) self.pixmap = QPixmap() self.pixmap.loadFromData(self.image_data) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation)) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def image_viewer(self, event=None): """pops up a image viewer to check the details""" dialog = QDialog() dialog.setWindowFlags(Qt.WindowTitleHint | Qt.WindowStaysOnTopHint) layout = QHBoxLayout(dialog) label = QLabel(dialog) # self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation) label.setPixmap(self.pixmap) label.setScaledContents(True) layout.addWidget(label) dialog.exec_() def open_file(self): """ saves the file """ dialog = QFileDialog(self) dialog.setNameFilter("Image Files (*.png *.jpg *.bmp)") dialog.setStyleSheet('color:black;') name = '' if dialog.exec_(): name = dialog.selectedFiles() if name: self.image_data = open(name[0], 'rb').read() self.pixmap = QPixmap(name[0]) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation)) def create_report(self): """ Creates a new Report """ try: data = self.get_data() if data: status = self.backend_handle.create_report(data=data) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) self.create_button.setHidden(True) self.delete_button.setVisible(True) self.update_button.setVisible(True) self.code = data['code'] self.update_data() else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def update_report(self): """ Updates an existing Report """ try: data = self.get_data() if data: status = self.backend_handle.update_report(data=data) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def get_data(self): """ Gets the data from the form as a dictionary :return:dictionary """ try: data = {} data['code'] = self.code_line.text() data['date'] = self.date_line.text() data['organization'] = self.organization_line.text() data['test'] = self.test_line.text() data['description'] = self.description_line.text() data['report'] = self.image_data for key, value in data.iteritems(): if not value: QMessageBox.critical( self, 'Error', 'Insert Proper value for %s' % key.title(), QMessageBox.Ok) return False return data except Exception: if settings.level == 10: logger.exception('raised exception') return False def delete_report(self): """ Deletes the existing report :return: """ try: code = self.code_line.text() status = self.backend_handle.delete_report(code=code) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) self.close() else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def calculate_code(self): """ Calculates the entry number, Eases the user for entering the code """ try: table = self.table if table: code = [] rows = table.rowCount() for row in range(rows): code.append(table.item(row, 0).text()) if code: new_code = str(int(max(code)) + 1) self.code_line.setText(new_code) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error'
def setupUi(self): layout = QGridLayout() inputs_grid = QHBoxLayout() self.inputs = QButtonGroup() def ifDevice(deviceID, func): if self.controller.hasDevice(deviceID): return func() return (None, None, None, None) def setCamera(cam, cc): if self.joystickAdapter: self.joystickAdapter.set_camera(cam) self.joystickAdapter.set_on_move(cc.deselectPreset) def makeCamera(videoSource, cameraID): cam = self.controller[cameraID] cc = CameraControl(cam) return ( videoSource, cc, AdvancedCameraControl(cameraID, cam, self.mainWindow), lambda: setCamera(cam, cc) ) def deselectCamera(): if self.joystickAdapter: self.joystickAdapter.set_camera(None) self.joystickAdapter.set_on_move(None) self.input_buttons_config = [ ifDevice("Camera 1", lambda: makeCamera(VideoSource.INPUT_1, "Camera 1")), ifDevice("Camera 2", lambda: makeCamera(VideoSource.INPUT_2, "Camera 2")), ifDevice("Camera 3", lambda: makeCamera(VideoSource.INPUT_3, "Camera 3")), (VideoSource.INPUT_4, QLabel(StringConstants.noDevice), None, deselectCamera), (VideoSource.INPUT_5, OverlayControl(self.switcherState.dsks[0], self.atem), None, deselectCamera), (VideoSource.INPUT_6, QLabel(StringConstants.noDevice), None, deselectCamera) ] for source, panel, adv_panel, on_select_func in self.input_buttons_config: if source: btn = InputButton(self.switcherState.inputs[source]) btn.setProperty("panel", panel) btn.setProperty("adv_panel", adv_panel) btn.clicked.connect(self.preview) btn.clicked.connect(self.displayPanel) if on_select_func: btn.clicked.connect(on_select_func) btn.longpress.connect(self.displayAdvPanel) self.inputs.addButton(btn) inputs_grid.addWidget(btn) self.extrasBtn = InputButton(None) self.inputs.addButton(self.extrasBtn) self.extrasBtn.clicked.connect(self.preview) self.extrasBtn.clicked.connect(self.displayPanel) self.extrasBtn.clicked.connect(deselectCamera) # An empty menu means the button will be given a "down arrow" icon # without actually showing a menu when pressed. self.extrasBtn.setMenu(QMenu()) self.allInputs = AllInputsPanel(self.switcherState) self.extrasBtn.setProperty("panel", self.allInputs) self.allInputs.inputSelected.connect(self.setExtraInput) inputs_grid.addWidget(self.extrasBtn) self.blackBtn = FlashingInputButton(self.switcherState.inputs[VideoSource.BLACK]) inputs_grid.addWidget(self.blackBtn) self.inputs.addButton(self.blackBtn) self.blackBtn.clicked.connect(self.preview) self.blackBtn.clicked.connect(self.displayPanel) self.blackBtn.clicked.connect(deselectCamera) self.ftb = FadeToBlackControl(self.switcherState.ftb, self.atem) self.blackBtn.setProperty("panel", self.ftb) self.blackBtn.flashing = self.switcherState.ftb.active self.switcherState.ftb.activeChanged.connect(self.blackBtn.setFlashing) layout.addLayout(inputs_grid, 0, 0, 1, 7) self.og = OutputsGrid(self.switcherState) self.og.take.connect(self.take) self.og.cut.connect(self.cut) self.og.selected.connect(self.sendToAux) self.og.mainToAll.connect(self.sendMainToAllAuxes) self.og.all.connect(self.sendToAll) self.og.sendMain.connect(self.sendMainToAux) self.og.setAuxesEnabled(False) # since we start off without an input selected layout.addWidget(self.og, 1, 5, 1, 2) self.blankWidget = QWidget() layout.addWidget(self.blankWidget, 1, 0, 1, 5) layout.setRowStretch(0, 1) layout.setRowStretch(1, 5) self.setLayout(layout)
class AnyIMU_window(QMainWindow): def __init__(self, parent=None): super(AnyIMU_window, self).__init__(parent) self.setWindowTitle('AnyIMU') self.resize(450, 700) os.system('cls') self.dcm = DCM() self.accDataCurr = None self.gyrDataCurr = None self.magDataCurr = None self.barDataCurr = None self.serialThread = None self.skipDataCount = 5 # The plot widget self.accPlotWidget = SensorDisplay(name='Accelerometer') self.gyrPlotWidget = SensorDisplay(name='Gyroscope') self.magPlotWidget = SensorDisplay(name='Magnetometer') self.barPlotWidget = SensorDisplay(name='Barometer') self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X') self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y') self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z') self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X') self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y') self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z') self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X') self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y') self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z') self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='float', dataName='TEMP') self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='float', dataName='PRS') self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='float', dataName='ALT') # the main layout and widgets self.mainWidget = QWidget() self.setCentralWidget(self.mainWidget) self.mainLayout = QGridLayout() self.mainWidget.setLayout(self.mainLayout) connectionLayout = QHBoxLayout() # widgets serialLab = QLabel('Serial Port:') self.serialLine = QLineEdit('COM3') self.serialLine.setFixedWidth(100) baudRateLab = QLabel('Baud Rate:') self.baudRateCombo = QComboBox() for baud in [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200]: self.baudRateCombo.addItem(str(baud)) default = self.baudRateCombo.findText('9600') self.baudRateCombo.setCurrentIndex(default) self.viewport = Viewport() # Debugging stuff---------------------------------- debugLayout = QHBoxLayout() # these are used to offset the the rotation self.xAdd = QSpinBox() self.yAdd = QSpinBox() self.zAdd = QSpinBox() for each in [self.xAdd, self.yAdd, self.zAdd]: each.setMinimum(-180) # min each.setMaximum(180) # max each.setSingleStep(90) # change this to a small value if need be # these are used for inverting the rotations self.xMult = QCheckBox() self.yMult = QCheckBox() self.zMult = QCheckBox() self.xAdd.setValue(0) self.yAdd.setValue(90) # in my case I need to offset by 90 in the Y axis self.zAdd.setValue(0) self.xMult.setChecked(False) self.yMult.setChecked(True) # in my case I need to invert the Y axis on the acc self.zMult.setChecked(False) for each in [self.xAdd, self.yAdd, self.zAdd, self.xMult, self.yMult, self.zMult]: debugLayout.addWidget(each) # Debugging stuff---------------------------------- self.serialBtn = QPushButton('Connect') # add widgets to layout connectionLayout.addWidget(serialLab) connectionLayout.addWidget(self.serialLine) connectionLayout.addWidget(baudRateLab) connectionLayout.addWidget(self.baudRateCombo) connectionLayout.addWidget(self.serialBtn) connectionLayout.addStretch() self.mainLayout.addLayout(connectionLayout, 0,0,1,2) self.mainLayout.addWidget(self.viewport, 1,0,1,2) self.mainLayout.addWidget(self.accPlotWidget, 2,0,1,1) self.mainLayout.addWidget(self.gyrPlotWidget, 2,1,1,1) self.mainLayout.addWidget(self.magPlotWidget, 3,0,1,1) self.mainLayout.addWidget(self.barPlotWidget, 3,1,1,1) self.mainLayout.addLayout(debugLayout, 4,0,1,2) self.serialBtn.clicked.connect(self.serialBtnCmd) self.serialBtnCmd() # --------------------------------------------------------------------------------------- def setupSerialThread(self): portVal = self.serialLine.text() baudRate = int(self.baudRateCombo.currentText()) self.serialThread = SerialThread() self.serialThread.serialConn(portVal, baudRate) self.serialThread.progress.connect(self.update, Qt.QueuedConnection) if not self.serialThread.isRunning(): self.serialThread.start() # --------------------------------------------------------------------------------------- def update(self, line): if self.skipDataCount: # skip the first couple lines of data, because there could be some junk self.skipDataCount-=1 return try: data = map(float, line.split(',')) dataChunks =[data[x:x+3] for x in xrange(0, len(data), 3)] except ValueError, e: print 'ERROR', e return self.accDataCurr = map(int, dataChunks[0]) self.gyrDataCurr = map(int, dataChunks[1]) self.magDataCurr = map(int, dataChunks[2]) self.barDataCurr = dataChunks[3] self.accPlotWidget.update(self.accDataCurr) self.gyrPlotWidget.update(self.gyrDataCurr) self.magPlotWidget.update(self.magDataCurr) self.barPlotWidget.update(self.barDataCurr) eulerAngles = self.dcm.update(self.accDataCurr, self.gyrDataCurr, self.magDataCurr) self.viewport.updateView(eulerAngles)
def initUI(self): layout = QGridLayout() self.setLayout(layout) self.btnUp = CameraButton() layout.addWidget(self.btnUp, 0, 1, 2, 1) _safelyConnect(self.btnUp.pressed, lambda: self.camera.moveUp(self.panSpeed, self.tiltSpeed)) _safelyConnect(self.btnUp.released, self.camera.stop) _safelyConnect(self.btnUp.clicked, self.deselectPreset) self.btnUp.setIcon(QIcon(":icons/go-up")) self.btnLeft = CameraButton() layout.addWidget(self.btnLeft, 1, 0, 2, 1) _safelyConnect(self.btnLeft.pressed, lambda: self.camera.moveLeft(self.panSpeed, self.tiltSpeed)) _safelyConnect(self.btnLeft.released, self.camera.stop) _safelyConnect(self.btnLeft.clicked, self.deselectPreset) self.btnLeft.setIcon(QIcon(":icons/go-previous")) self.btnDown = CameraButton() layout.addWidget(self.btnDown, 2, 1, 2, 1) _safelyConnect(self.btnDown.pressed, lambda: self.camera.moveDown(self.panSpeed, self.tiltSpeed)) _safelyConnect(self.btnDown.released, self.camera.stop) _safelyConnect(self.btnDown.clicked, self.deselectPreset) self.btnDown.setIcon(QIcon(":icons/go-down")) self.btnRight = CameraButton() layout.addWidget(self.btnRight, 1, 2, 2, 1) _safelyConnect(self.btnRight.pressed, lambda: self.camera.moveRight(self.panSpeed, self.tiltSpeed)) _safelyConnect(self.btnRight.released, self.camera.stop) _safelyConnect(self.btnRight.clicked, self.deselectPreset) self.btnRight.setIcon(QIcon(":icons/go-next")) zoomInOut = PlusMinusButtons("Zoom") _safelyConnect(zoomInOut.upButton.pressed, lambda: self.camera.zoomIn(self.zoomSpeed)) _safelyConnect(zoomInOut.upButton.released, self.camera.zoomStop) _safelyConnect(zoomInOut.upButton.clicked, self.deselectPreset) _safelyConnect(zoomInOut.downButton.pressed, lambda: self.camera.zoomOut(self.zoomSpeed)) _safelyConnect(zoomInOut.downButton.released, self.camera.zoomStop) _safelyConnect(zoomInOut.downButton.clicked, self.deselectPreset) layout.addWidget(zoomInOut, 0, 3, 4, 1) focus = PlusMinusAutoButtons("Focus") _safelyConnect(focus.upButton.pressed, self.camera.focusFar) _safelyConnect(focus.upButton.released, self.camera.focusStop) _safelyConnect(focus.upButton.clicked, self.deselectPreset) _safelyConnect(focus.downButton.pressed, self.camera.focusNear) _safelyConnect(focus.downButton.released, self.camera.focusStop) _safelyConnect(focus.downButton.clicked, self.deselectPreset) def autoFocusAndDeselect(): self.camera.focusAuto() self.deselectPreset() _safelyConnect(focus.autoButton.clicked, autoFocusAndDeselect) layout.addWidget(focus, 0, 4, 4, 1) brightness = PlusMinusAutoButtons("Bright") _safelyConnect(brightness.upButton.clicked, self.camera.brighter) _safelyConnect(brightness.downButton.clicked, self.camera.darker) _safelyConnect(brightness.autoButton.clicked, self.camera.setAutoExposure) layout.addWidget(brightness, 0, 5, 4, 1) presets = QGridLayout() presets.setRowStretch(0, 2) presets.setRowStretch(1, 1) self.presetGroup = QButtonGroup() for i in range(1, 7): btnPresetRecall = CameraButton() presets.addWidget(btnPresetRecall, 0, i, 1, 1) btnPresetRecall.setText(str(i)) _safelyConnect(btnPresetRecall.clicked, lambda i=i: self.recallPreset(i)) btnPresetRecall.setCheckable(True) self.presetGroup.addButton(btnPresetRecall, i) btnPresetSet = CameraButton() presets.addWidget(btnPresetSet, 1, i, 1, 1) btnPresetSet.setText("Set") _safelyConnect(btnPresetSet.clicked, lambda i=i: self.storePreset(i)) layout.addLayout(presets, 4, 0, 3, 6)
def __init__(self, parent): super(MainControl, self).__init__(parent) self.parent = parent self.selectedMinerals = parent.selectedMinerals self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) lb0 = QLabel('Minecraft Prism chunk minerals finder') lb1 = QLabel('Chunk X') lb2 = QLabel('Chunk Z') lb3 = QLabel('Show deposits of:') lb4 = QLabel('Slice Elevation') #lb0.setFrameStyle(QFrame.Box) lb0.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) lb2.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.txtChunkX = QLineEdit() self.txtChunkZ = QLineEdit() self.txtElevation = QLineEdit(str(self.parent.presenter.elevation)) self.txtChunkX.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.txtChunkZ.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.txtElevation.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.btnViewChunk = QPushButton('View Chunk') self.btnViewChunk.clicked.connect(self.btnViewChunk_OnClick) self.btnSliceUp = QPushButton('Slice Up') self.btnSliceUp.clicked.connect(self.btnSliceUp_OnClick) self.btnSliceDown = QPushButton('Slice Down') self.btnSliceDown.clicked.connect(self.btnSliceDown_OnClick) self.lstMinerals = QListWidget() self.lstMinerals.setSelectionMode(QAbstractItemView.ExtendedSelection) self.lstMinerals.addItem(SelectedMineral('Gold', 14)) self.lstMinerals.addItem(SelectedMineral('Iron', 15)) self.lstMinerals.addItem(SelectedMineral('Diamond', 56)) self.lstMinerals.addItem(SelectedMineral('Redstone', 73)) self.lstMinerals.addItem(SelectedMineral('Obsidian', 49)) self.lstMinerals.addItem(SelectedMineral('Coal', 16)) self.lstMinerals.addItem(SelectedMineral('Lazurit', 21)) self.lstMinerals.setCurrentItem(self.lstMinerals.item(0)) self.lstMinerals.itemSelectionChanged.connect(self.onSelectedMinerals) elevBox = QHBoxLayout() elevBox.addWidget(lb4) elevBox.addWidget(self.txtElevation) elevBox.addWidget(self.btnSliceUp) elevBox.addWidget(self.btnSliceDown) ly = QGridLayout() ly.addWidget(lb0, 0, 0, 1, 4) ly.addWidget(lb1, 1, 0, 1, 1) ly.addWidget(self.txtChunkX, 1, 1, 1, 1) ly.addWidget(lb2, 1, 2, 1, 1) ly.addWidget(self.txtChunkZ, 1, 3, 1, 1) ly.addWidget(lb3, 2, 0, 1, 2) ly.addWidget(self.lstMinerals, 2, 2, 1, 2) ly.addWidget(self.btnViewChunk, 3, 1, 1, 2) ly.addLayout(elevBox, 4, 0, 1, 4) ly.setColumnStretch(0, 20) ly.setColumnStretch(1, 15) ly.setColumnStretch(2, 46) ly.setColumnStretch(3, 19) self.setLayout(ly)
def __init__(self): super().__init__() if separate_colorbars: if rescale_colorbars: self.vmins = tuple(np.min(u[0]) for u in U) self.vmaxs = tuple(np.max(u[0]) for u in U) else: self.vmins = tuple(np.min(u) for u in U) self.vmaxs = tuple(np.max(u) for u in U) else: if rescale_colorbars: self.vmins = (min(np.min(u[0]) for u in U), ) * len(U) self.vmaxs = (max(np.max(u[0]) for u in U), ) * len(U) else: self.vmins = (min(np.min(u) for u in U), ) * len(U) self.vmaxs = (max(np.max(u) for u in U), ) * len(U) layout = QHBoxLayout() plot_layout = QGridLayout() self.colorbarwidgets = [ cbar_widget(self, vmin=vmin, vmax=vmax) if cbar_widget else None for vmin, vmax in zip(self.vmins, self.vmaxs) ] plots = [ widget(self, grid, vmin=vmin, vmax=vmax, bounding_box=bounding_box, codim=codim) for vmin, vmax in zip(self.vmins, self.vmaxs) ] if legend: for i, plot, colorbar, l in zip( range(len(plots)), plots, self.colorbarwidgets, legend): subplot_layout = QVBoxLayout() caption = QLabel(l) caption.setAlignment(Qt.AlignHCenter) subplot_layout.addWidget(caption) if not separate_colorbars or backend == 'matplotlib': subplot_layout.addWidget(plot) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) if colorbar: hlayout.addWidget(colorbar) subplot_layout.addLayout(hlayout) plot_layout.addLayout(subplot_layout, int(i / columns), (i % columns), 1, 1) else: for i, plot, colorbar in zip(range(len(plots)), plots, self.colorbarwidgets): if not separate_colorbars or backend == 'matplotlib': plot_layout.addWidget(plot, int(i / columns), (i % columns), 1, 1) else: hlayout = QHBoxLayout() hlayout.addWidget(plot) if colorbar: hlayout.addWidget(colorbar) plot_layout.addLayout(hlayout, int(i / columns), (i % columns), 1, 1) layout.addLayout(plot_layout) if not separate_colorbars: layout.addWidget(self.colorbarwidgets[0]) for w in self.colorbarwidgets[1:]: w.setVisible(False) self.setLayout(layout) self.plots = plots
def __init__(self, controller): super(MainWindow, self).__init__() self.controller = controller self.setWindowTitle("av-control") self.resize(1024, 600) self.setWindowIcon(QIcon(":icons/video-display")) self.mainScreen = VideoSwitcher(controller, self) self.stack = QStackedWidget() self.stack.addWidget(self.mainScreen) outer = QWidget() mainLayout = QGridLayout() mainLayout.addWidget(self.stack, 0, 0, 1, 7) column = 0 self.spc = SystemPowerWidget(controller, self) syspower = ExpandingButton() syspower.setText("Power") syspower.clicked.connect(self.showSystemPower) syspower.setIcon(QIcon(":icons/system-shutdown")) syspower.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(syspower, 1, column) column += 1 self.bc = BlindsControl(controller["Blinds"], self) blinds = ExpandingButton() blinds.setText("Blinds") blinds.clicked.connect(lambda: self.showScreen(self.bc)) blinds.setIcon(QIcon(":icons/blinds")) blinds.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(blinds, 1, column) column += 1 self.sc = ProjectorScreensControl(controller["Screens"], self) screens = ExpandingButton() screens.setText("Screens") screens.clicked.connect(lambda: self.showScreen(self.sc)) screens.setIcon(QIcon(":icons/screens")) screens.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(screens, 1, column) column += 1 if controller.hasDevice("Lights"): self.lightsMenu = LightingControl(controller["Lights"], self) lights = ExpandingButton() lights.setText("Lights") lights.clicked.connect(lambda: self.showScreen(self.lightsMenu)) lights.setIcon(QIcon(":icons/lightbulb_on")) lights.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) mainLayout.addWidget(lights, 1, column) column += 1 self.advMenu = AdvancedMenu(self.controller, self) adv = ExpandingButton() adv.setText("Advanced") adv.setIcon(QIcon(":icons/applications-system")) adv.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) adv.clicked.connect(lambda: self.showScreen(self.advMenu)) mainLayout.addWidget(adv, 1, column) column += 1 for i in range(column): mainLayout.setColumnStretch(i, 1) tray = QHBoxLayout() tray.addWidget(Clock()) tray.addWidget(SystemStatus(controller)) mainLayout.addLayout(tray, 1, column) mainLayout.setRowStretch(0, 8) mainLayout.setRowStretch(1, 0) outer.setLayout(mainLayout) self.setCentralWidget(outer) self.pnd = PowerNotificationDialog(self) self.pnd.accepted.connect(self.hidePowerDialog)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setWindowTitle('Runner') self.setMinimumWidth(750) # Runner self._runner = None self._running_timer = QTimer() self._running_timer.setInterval(500) # Widgets self._dlg_progress = QProgressDialog() self._dlg_progress.setRange(0, 100) self._dlg_progress.setModal(True) self._dlg_progress.hide() lbl_outputdir = QLabel("Output directory") self._txt_outputdir = DirBrowseWidget() max_workers = cpu_count() #@UndefinedVariable lbl_workers = QLabel('Number of workers') self._spn_workers = QSpinBox() self._spn_workers.setRange(1, max_workers) self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) lbl_max_workers = QLabel('(max: %i)' % max_workers) self._chk_overwrite = QCheckBox("Overwrite existing results in output directory") self._chk_overwrite.setChecked(True) self._lbl_available = QLabel('Available') self._lst_available = QListView() self._lst_available.setModel(_AvailableOptionsListModel()) self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection) tlb_available = QToolBar() spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) tlb_available.addWidget(spacer) act_open = tlb_available.addAction(getIcon("document-open"), "Open") act_open.setShortcut(QKeySequence.Open) tlb_available.addSeparator() act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove") act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear") self._btn_addtoqueue = QPushButton(getIcon("go-next"), "") self._btn_addtoqueue.setToolTip("Add to queue") self._btn_addtoqueue.setEnabled(False) self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "") self._btn_addalltoqueue.setToolTip("Add all to queue") self._btn_addalltoqueue.setEnabled(False) self._lbl_options = QLabel('Queued/Running/Completed') self._tbl_options = QTableView() self._tbl_options.setModel(_StateOptionsTableModel()) self._tbl_options.setItemDelegate(_StateOptionsItemDelegate()) self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection) self._tbl_options.setColumnWidth(1, 60) self._tbl_options.setColumnWidth(2, 80) header = self._tbl_options.horizontalHeader() header.setResizeMode(0, QHeaderView.Interactive) header.setResizeMode(1, QHeaderView.Fixed) header.setResizeMode(2, QHeaderView.Fixed) header.setResizeMode(3, QHeaderView.Stretch) self._btn_start = QPushButton(getIcon("media-playback-start"), "Start") self._btn_cancel = QPushButton("Cancel") self._btn_cancel.setEnabled(False) self._btn_close = QPushButton("Close") self._btn_import = QPushButton("Import") self._btn_import.setEnabled(False) # Layouts layout = QVBoxLayout() sublayout = QGridLayout() sublayout.addWidget(lbl_outputdir, 0, 0) sublayout.addWidget(self._txt_outputdir, 0, 1) sublayout.addWidget(lbl_workers, 1, 0) subsublayout = QHBoxLayout() subsublayout.addWidget(self._spn_workers) subsublayout.addWidget(lbl_max_workers) sublayout.addLayout(subsublayout, 1, 1) layout.addLayout(sublayout) sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3) sublayout = QGridLayout() sublayout.setColumnStretch(0, 1) sublayout.setColumnStretch(2, 3) sublayout.addWidget(self._lbl_available, 0, 0) sublayout.addWidget(self._lst_available, 1, 0) sublayout.addWidget(tlb_available, 2, 0) subsublayout = QVBoxLayout() subsublayout.addStretch() subsublayout.addWidget(self._btn_addtoqueue) subsublayout.addWidget(self._btn_addalltoqueue) subsublayout.addStretch() sublayout.addLayout(subsublayout, 1, 1) sublayout.addWidget(self._lbl_options, 0, 2) sublayout.addWidget(self._tbl_options, 1, 2) layout.addLayout(sublayout) sublayout = QHBoxLayout() sublayout.addStretch() sublayout.addWidget(self._btn_import) sublayout.addWidget(self._btn_start) sublayout.addWidget(self._btn_cancel) sublayout.addWidget(self._btn_close) layout.addLayout(sublayout) self.setLayout(layout) # Signal self._running_timer.timeout.connect(self._onRunningTimer) act_open.triggered.connect(self._onOpen) act_remove.triggered.connect(self._onRemove) act_clear.triggered.connect(self._onClear) self._btn_addtoqueue.released.connect(self._onAddToQueue) self._btn_addalltoqueue.released.connect(self._onAddAllToQueue) self._btn_start.released.connect(self._onStart) self._btn_cancel.released.connect(self._onCancel) self._btn_close.released.connect(self._onClose) self._btn_import.released.connect(self._onImport) self.options_added.connect(self._onOptionsAdded) self.options_running.connect(self._onOptionsRunning) self.options_simulated.connect(self._onOptionsSimulated) self.options_error.connect(self._onOptionsError) self.results_error.connect(self._onResultsError) # Defaults settings = get_settings() section = settings.add_section('gui') if hasattr(section, 'outputdir'): self._txt_outputdir.setPath(section.outputdir) if hasattr(section, 'maxworkers'): self._spn_workers.setValue(int(section.maxworkers)) if hasattr(section, 'overwrite'): state = True if section.overwrite.lower() == 'true' else False self._chk_overwrite.setChecked(state)
class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(560, 560) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) Form.setMinimumSize(QtCore.QSize(0, 0)) self.gridLayout_2 = QGridLayout(Form) self.gridLayout_2.setObjectName("gridLayout_2") self.editorGroupBox = QGroupBox(Form) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.editorGroupBox.sizePolicy().hasHeightForWidth()) self.editorGroupBox.setSizePolicy(sizePolicy) self.editorGroupBox.setMinimumSize(QtCore.QSize(0, 0)) self.editorGroupBox.setObjectName("editorGroupBox") self.gridLayout_3 = QGridLayout(self.editorGroupBox) self.gridLayout_3.setObjectName("gridLayout_3") self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.variable_verticalLayout_1 = QVBoxLayout() self.variable_verticalLayout_1.setObjectName( "variable_verticalLayout_1") self.listBox = QListWidget(self.editorGroupBox) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.listBox.sizePolicy().hasHeightForWidth()) self.listBox.setSizePolicy(sizePolicy) self.listBox.setDragEnabled(True) self.listBox.setDragDropOverwriteMode(False) self.listBox.setDragDropMode(QAbstractItemView.InternalMove) self.listBox.setDefaultDropAction(QtCore.Qt.MoveAction) self.listBox.setAlternatingRowColors(True) self.listBox.setSelectionMode(QAbstractItemView.SingleSelection) self.listBox.setMovement(QListView.Snap) self.listBox.setResizeMode(QListView.Fixed) self.listBox.setSelectionRectVisible(False) self.listBox.setObjectName("listBox") self.variable_verticalLayout_1.addWidget(self.listBox) self.gridLayout.addLayout(self.variable_verticalLayout_1, 0, 0, 1, 1) self.variable_verticalLayout_2 = QVBoxLayout() self.variable_verticalLayout_2.setObjectName( "variable_verticalLayout_2") self.addButton = QPushButton(self.editorGroupBox) self.addButton.setObjectName("addButton") self.variable_verticalLayout_2.addWidget(self.addButton) self.editButton = QPushButton(self.editorGroupBox) self.editButton.setObjectName("editButton") self.variable_verticalLayout_2.addWidget(self.editButton) self.removeButton = QPushButton(self.editorGroupBox) self.removeButton.setObjectName("removeButton") self.variable_verticalLayout_2.addWidget(self.removeButton) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.variable_verticalLayout_2.addItem(spacerItem) self.upButton = QPushButton(self.editorGroupBox) self.upButton.setObjectName("upButton") self.variable_verticalLayout_2.addWidget(self.upButton) self.downButton = QPushButton(self.editorGroupBox) self.downButton.setObjectName("downButton") self.variable_verticalLayout_2.addWidget(self.downButton) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.variable_verticalLayout_2.addItem(spacerItem1) self.variable_verticalLayout_2.setStretch(3, 1) self.variable_verticalLayout_2.setStretch(6, 1) self.gridLayout.addLayout(self.variable_verticalLayout_2, 0, 1, 1, 1) self.gridLayout.setColumnStretch(0, 1) self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setContentsMargins(15, 15, 15, 15) self.horizontalLayout.setObjectName("horizontalLayout") spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem2) self.ok_pushButton = QPushButton(self.editorGroupBox) self.ok_pushButton.setObjectName("ok_pushButton") self.horizontalLayout.addWidget(self.ok_pushButton) self.cancel_pushButton = QPushButton(self.editorGroupBox) self.cancel_pushButton.setObjectName("cancel_pushButton") self.horizontalLayout.addWidget(self.cancel_pushButton) self.horizontalLayout.setStretch(0, 1) self.gridLayout_3.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.gridLayout_2.addWidget(self.editorGroupBox, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle( QApplication.translate("Form", "Form", None, QApplication.UnicodeUTF8)) self.editorGroupBox.setTitle( QApplication.translate("Form", "Maya Module Path Editor", None, QApplication.UnicodeUTF8)) self.addButton.setText( QApplication.translate("Form", "<<", None, QApplication.UnicodeUTF8)) self.editButton.setText( QApplication.translate("Form", "Edit", None, QApplication.UnicodeUTF8)) self.removeButton.setText( QApplication.translate("Form", ">>", None, QApplication.UnicodeUTF8)) self.upButton.setText( QApplication.translate("Form", "Move Up", None, QApplication.UnicodeUTF8)) self.downButton.setText( QApplication.translate("Form", "Move Down", None, QApplication.UnicodeUTF8)) self.ok_pushButton.setText( QApplication.translate("Form", "Save", None, QApplication.UnicodeUTF8)) self.cancel_pushButton.setText( QApplication.translate("Form", "Close", None, QApplication.UnicodeUTF8))
def setupUi(self): scene = QGraphicsScene(self) self.view = QGraphicsView(scene, self) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVisible(True) self.view.setInteractive(True) self.createPixmapIcon() self.mapWidget = MapWidget(self.mapManager) scene.addItem(self.mapWidget) self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95)) self.mapWidget.setZoomLevel(5) #... self.slider = QSlider(Qt.Vertical, self) self.slider.setTickInterval(1) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setMaximum(self.mapManager.maximumZoomLevel()) self.slider.setMinimum(self.mapManager.minimumZoomLevel()) self.slider.valueChanged[int].connect(self.sliderValueChanged) self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged) mapControlLayout = QVBoxLayout() self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged) for mapType in self.mapWidget.supportedMapTypes(): radio = QRadioButton(self) if mapType == QGraphicsGeoMap.StreetMap: radio.setText('Street') elif mapType == QGraphicsGeoMap.SatelliteMapDay: radio.setText('Sattelite') elif mapType == QGraphicsGeoMap.SatelliteMapNight: radio.setText('Sattelite - Night') elif mapType == QGraphicsGeoMap.TerrainMap: radio.setText('Terrain') if mapType == self.mapWidget.mapType(): radio.setChecked(True) radio.toggled[bool].connect(self.mapTypeToggled) self.mapControlButtons.append(radio) self.mapControlTypes.append(mapType) mapControlLayout.addWidget(radio) self.latitudeEdit = QLineEdit() self.longitudeEdit = QLineEdit() formLayout = QFormLayout() formLayout.addRow('Latitude', self.latitudeEdit) formLayout.addRow('Longitude', self.longitudeEdit) self.captureCoordsButton = QToolButton() self.captureCoordsButton.setText('Capture coordinates') self.captureCoordsButton.setCheckable(True) self.captureCoordsButton.toggled[bool].connect( self.mapWidget.setMouseClickCoordQuery) self.mapWidget.coordQueryResult.connect(self.updateCoords) self.setCoordsButton = QPushButton() self.setCoordsButton.setText('Set coordinates') self.setCoordsButton.clicked.connect(self.setCoordsClicked) buttonLayout = QHBoxLayout() buttonLayout.addWidget(self.captureCoordsButton) buttonLayout.addWidget(self.setCoordsButton) coordControlLayout = QVBoxLayout() coordControlLayout.addLayout(formLayout) coordControlLayout.addLayout(buttonLayout) widget = QWidget(self) layout = QGridLayout() layout.setRowStretch(0, 1) layout.setRowStretch(1, 0) topLayout = QGridLayout() bottomLayout = QGridLayout() topLayout.setColumnStretch(0, 0) topLayout.setColumnStretch(1, 1) bottomLayout.setColumnStretch(0, 0) bottomLayout.setColumnStretch(1, 1) topLayout.addWidget(self.slider, 0, 0) topLayout.addWidget(self.view, 0, 1) bottomLayout.addLayout(mapControlLayout, 0, 0) bottomLayout.addLayout(coordControlLayout, 0, 1) layout.addLayout(topLayout, 0, 0) layout.addLayout(bottomLayout, 1, 0) self.layout = layout widget.setLayout(layout) self.setCentralWidget(widget) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.customContextMenuRequest)
def makeContent(self): layout = QGridLayout() self.posDisplay = QGridLayout() self.posDisplay.addWidget(QLabel("Pan:"), 0, 0) self.posDisplay.addWidget(QLabel("Tilt:"), 1, 0) self.posDisplay.addWidget(QLabel("Zoom:"), 2, 0) self.posDisplay.addWidget(QLabel(), 0, 1) self.posDisplay.addWidget(QLabel(), 1, 1) self.posDisplay.addWidget(QLabel(), 2, 1) layout.addLayout(self.posDisplay, 1, 0) btnGetPos = ExpandingButton() btnGetPos.setText("Get Position") btnGetPos.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) layout.addWidget(btnGetPos, 2, 0) btnGetPos.clicked.connect(self.displayPosition) whiteBalanceGrid = QGridLayout() wbTitle = QLabel("White Balance") wbTitle.setAlignment(Qt.AlignCenter) whiteBalanceGrid.addWidget(wbTitle, 0, 0, 1, 2) btnAuto = OptionButton() btnAuto.setText("Auto") btnAuto.clicked.connect(lambda: self.controller.whiteBalance(self.cameraID, CameraWhiteBalance.Auto)) whiteBalanceGrid.addWidget(btnAuto, 1, 0) btnIndoor = OptionButton() btnIndoor.setText("Indoor") btnIndoor.clicked.connect(lambda: self.controller.whiteBalance(self.cameraID, CameraWhiteBalance.Indoor)) whiteBalanceGrid.addWidget(btnIndoor, 2, 0) btnOutdoor = OptionButton() btnOutdoor.setText("Outdoor") btnOutdoor.clicked.connect(lambda: self.controller.whiteBalance(self.cameraID, CameraWhiteBalance.Outdoor)) whiteBalanceGrid.addWidget(btnOutdoor, 3, 0) btnOnePush = OptionButton() btnOnePush.setText("One Push") btnOnePush.clicked.connect(lambda: self.controller.whiteBalance(self.cameraID, CameraWhiteBalance.OnePush)) whiteBalanceGrid.addWidget(btnOnePush, 4, 0) btnOnePushTrigger = ExpandingButton() btnOnePushTrigger.setText("Set") btnOnePushTrigger.clicked.connect(lambda: self.controller.whiteBalance(self.cameraID, CameraWhiteBalance.Trigger)) btnOnePushTrigger.setEnabled(False) whiteBalanceGrid.addWidget(btnOnePushTrigger, 4, 1) self.wbOpts = QButtonGroup() self.wbOpts.addButton(btnAuto, 1) self.wbOpts.addButton(btnIndoor, 2) self.wbOpts.addButton(btnOutdoor, 3) self.wbOpts.addButton(btnOnePush, 4) self.wbOpts.buttonClicked.connect(lambda: btnOnePushTrigger.setEnabled(self.wbOpts.checkedId() == 4)) layout.addLayout(whiteBalanceGrid, 1, 1, 2, 1) return layout