def __init__(self, targetImage=None, axeSize=500, layer=None, parent=None): super().__init__(layer=layer, targetImage=targetImage, parent=parent) ####################################### # Libraw correspondences: # rgb_xyz_matrix is libraw cam_xyz # camera_whitebalance is libraw cam_mul # daylight_whitebalance is libraw pre_mul # dng correspondences: # ASSHOTNEUTRAL tag value is (X,Y,Z) = 1 / rawpyObj.camera_whitebalance ########################################## rawpyObj = layer.parentImage.rawImage # constants and as shot values self.XYZ2CameraMatrix = rawpyObj.rgb_xyz_matrix[:3, :] self.XYZ2CameraInverseMatrix = np.linalg.inv(self.XYZ2CameraMatrix) # initial post processing multipliers (as shot) m1, m2, m3, m4 = rawpyObj.camera_whitebalance self.asShotMultipliers = ( m1 / m2, 1.0, m3 / m2, m4 / m2 ) # normalization is mandatory : for nef files white balance is around 256 self.asShotTemp, self.asShotTint = multipliers2TemperatureAndTint( *1 / np.array(self.asShotMultipliers[:3]), self.XYZ2CameraMatrix) self.rawMultipliers = self.asShotMultipliers # rawpyObj.camera_whitebalance # = 1/(dng ASSHOTNEUTRAL tag value) self.sampleMultipliers = False self.samples = [] ######################################## # XYZ-->Camera conversion matrix: # Last row is zero for RGB cameras (cf. rawpy and libraw docs). # type ndarray, shape (4,3) ######################################### # attributes initialized in setDefaults, declared here for the sake of correctness self.tempCorrection, self.tintCorrection, self.expCorrection, self.highCorrection,\ self.contCorrection, self.satCorrection, self.brCorrection = [None] * 7 # contrast spline vie (initialized by setContrastSpline) self.contrastForm = None # tone spline view (initialized by setToneSpline) self.toneForm = None # dock containers for contrast and tome forms self.dockC, self.dockT = None, None # options optionList0, optionNames0 = ['Auto Brightness', 'Preserve Highlights' ], ['Auto Expose', 'Preserve Highlights'] optionList1, optionNames1 = ['Auto WB', 'Camera WB', 'User WB' ], ['Auto', 'Camera (As Shot)', 'User'] optionList2, optionNames2 = [ 'cpLookTable', 'cpToneCurve', 'manualCurve' ], [ 'Use Camera Profile Look Table', 'Show Tone Curves', 'Show Contrast Curve' ] self.listWidget1 = optionsWidget( options=optionList0, optionNames=optionNames0, exclusive=False, changed=lambda: self.dataChanged.emit(1)) self.listWidget2 = optionsWidget( options=optionList1, optionNames=optionNames1, exclusive=True, changed=lambda: self.dataChanged.emit(1)) self.listWidget3 = optionsWidget( options=optionList2, optionNames=optionNames2, exclusive=False, changed=lambda: self.dataChanged.emit(2)) self.options = UDict( (self.listWidget1.options, self.listWidget2.options, self.listWidget3.options)) # display the 'as shot' temperature item = self.listWidget2.item(1) item.setText(item.text() + ' : %d' % self.asShotTemp) # temperature slider self.sliderTemp = QbLUeSlider(Qt.Horizontal) self.sliderTemp.setStyleSheet( QbLUeSlider.bLueSliderDefaultColorStylesheet) self.sliderTemp.setRange(0, 100) self.sliderTemp.setSingleStep(1) self.tempLabel = QLabel() self.tempLabel.setText("Temp") self.tempValue = QLabel() font = self.tempValue.font() metrics = QFontMetrics(font) w = metrics.width("10000") h = metrics.height() self.tempValue.setMinimumSize(w, h) self.tempValue.setMaximumSize(w, h) self.tempValue.setText( str("{:.0f}".format(self.slider2Temp(self.sliderTemp.value())))) self.sliderTemp.valueChanged.connect( self.tempUpdate) # signal send new value as parameter self.sliderTemp.sliderReleased.connect(lambda: self.tempUpdate( self.sliderTemp.value())) # signal pass no parameter # tint slider self.sliderTint = QbLUeSlider(Qt.Horizontal) self.sliderTint.setStyleSheet( QbLUeSlider.bLueSliderDefaultIMGColorStylesheet) self.sliderTint.setRange(0, 150) self.sliderTint.setSingleStep(1) self.tintLabel = QLabel() self.tintLabel.setText("Tint") self.tintValue = QLabel() font = self.tempValue.font() metrics = QFontMetrics(font) w = metrics.width("100") h = metrics.height() self.tintValue.setMinimumSize(w, h) self.tintValue.setMaximumSize(w, h) self.tintValue.setText( str("{:.0f}".format(self.sliderTint2User( self.sliderTint.value())))) self.sliderTint.valueChanged.connect(self.tintUpdate) self.sliderTint.sliderReleased.connect(lambda: self.tintUpdate( self.sliderTint.value())) # signal pass no parameter) ###################### # From libraw and dcraw sources: # Exposure and brightness are curve transformations. # Exposure curve is y = alpha*x, with cubic root ending; it is applied before demosaicing. # Brightness is (similar to) y = x**alpha and part of gamma transformation from linear sRGB to RGB. # Exposure and brightness both dilate the histogram towards highlights. # Exposure dilatation is uniform (homothety), brightness dilataion is # maximum for the midtones and the highlghts are preserved. # As a consequence, normal workflow begins with the adjustment of exposure, # to fill the entire range of the histogram and to adjust the highlights. Next, # one adjusts the brightness to put the midtones at the level we want them to be. # Cf. https://www.cambridgeincolour.com/forums/thread653.htm ##################### # profile combo self.dngDict = self.setCameraProfilesCombo() # cameraProfilesCombo index changed event handler def cameraProfileUpdate(value): self.dngDict = self.cameraProfilesCombo.itemData(value) if self.options['cpToneCurve']: toneCurve = dngProfileToneCurve( self.dngDict.get('ProfileToneCurve', [])) self.toneForm.baseCurve = [ QPointF(x * axeSize, -y * axeSize) for x, y in zip(toneCurve.dataX, toneCurve.dataY) ] self.toneForm.update() # recompute as shot temp and tint using new profile self.asShotTemp, self.asShotTint = multipliers2TemperatureAndTint( *1 / np.array(self.asShotMultipliers[:3]), self.XYZ2CameraMatrix, dngDict=self.dngDict ) # TODO 6/12/19 added keyword dngDict validate # display updated as shot temp item = self.listWidget2.item(1) item.setText(item.text().split(":")[0] + ': %d' % self.asShotTemp) # invalidate cache self.layer.bufCache_HSV_CV32 = None self.dataChanged.emit(2) # 2 = no postprocessing self.cameraProfilesCombo.currentIndexChanged.connect( cameraProfileUpdate) # denoising combo self.denoiseCombo = QComboBox() items = OrderedDict([('Off', 0), ('Medium', 1), ('Full', 2)]) for key in items: self.denoiseCombo.addItem(key, items[key]) # denoiseCombo index changed event handler def denoiseUpdate(value): self.denoiseValue = self.denoiseCombo.itemData(value) self.dataChanged.emit(1) self.denoiseCombo.currentIndexChanged.connect(denoiseUpdate) # overexposed area restoration self.overexpCombo = QComboBox() items = OrderedDict([('Clip', 0), ('Ignore', 1), ('Blend', 2), ('Reconstruct', 3)]) for key in items: self.overexpCombo.addItem(key, items[key]) # overexpCombo index changed event handler def overexpUpdate(value): self.overexpValue = self.overexpCombo.itemData(value) self.dataChanged.emit(1) self.overexpCombo.currentIndexChanged.connect(overexpUpdate) # exp slider self.sliderExp = QbLUeSlider(Qt.Horizontal) self.sliderExp.setStyleSheet(QbLUeSlider.bLueSliderDefaultBWStylesheet) self.sliderExp.setRange(0, 100) self.sliderExp.setSingleStep(1) self.expLabel = QLabel() self.expLabel.setText("Exp.") self.expValue = QLabel() font = self.expValue.font() metrics = QFontMetrics(font) w = metrics.width("+1.0") h = metrics.height() self.expValue.setMinimumSize(w, h) self.expValue.setMaximumSize(w, h) self.expValue.setText( str("{:.1f}".format(self.slider2Exp(self.sliderExp.value())))) # exp done event handler def expUpdate(value): self.expValue.setText( str("{:+.1f}".format( self.sliderExp2User(self.sliderExp.value())))) # move not yet terminated or value not modified if self.sliderExp.isSliderDown() or self.slider2Exp( value) == self.expCorrection: return try: self.sliderExp.valueChanged.disconnect() self.sliderExp.sliderReleased.disconnect() except RuntimeError: pass # rawpy: expCorrection range is -2.0...3.0, boiling down to exp_shift range 2**(-2)=0.25...2**3=8.0 self.expCorrection = self.slider2Exp(self.sliderExp.value()) self.dataChanged.emit(1) self.sliderExp.valueChanged.connect( expUpdate) # send new value as parameter self.sliderExp.sliderReleased.connect(lambda: expUpdate( self.sliderExp.value())) # signal pass no parameter self.sliderExp.valueChanged.connect( expUpdate) # send new value as parameter self.sliderExp.sliderReleased.connect(lambda: expUpdate( self.sliderExp.value())) # signal pass no parameter # brightness slider brSlider = QbLUeSlider(Qt.Horizontal) brSlider.setRange(1, 101) self.sliderExp.setSingleStep(1) brSlider.setStyleSheet(QbLUeSlider.bLueSliderDefaultBWStylesheet) self.sliderBrightness = brSlider brLabel = QLabel() brLabel.setText("Bright.") self.brValue = QLabel() font = self.expValue.font() metrics = QFontMetrics(font) w = metrics.width("+99") h = metrics.height() self.brValue.setMinimumSize(w, h) self.brValue.setMaximumSize(w, h) self.brValue.setText( str("{:+d}".format( int(self.brSlider2User(self.sliderBrightness.value()))))) # brightness done event handler def brUpdate(value): self.brValue.setText( str("{:+d}".format( int(self.brSlider2User(self.sliderBrightness.value()))))) # move not yet terminated or value not modified if self.sliderBrightness.isSliderDown() or self.slider2Br( value) == self.brCorrection: return try: self.sliderBrightness.valueChanged.disconnect() self.sliderBrightness.sliderReleased.disconnect() except RuntimeError: pass self.brCorrection = self.slider2Br(self.sliderBrightness.value()) self.dataChanged.emit(1) self.sliderBrightness.sliderReleased.connect( lambda: brUpdate(self.sliderBrightness.value())) self.sliderBrightness.valueChanged.connect( brUpdate) # send new value as parameter self.sliderBrightness.valueChanged.connect( brUpdate) # send new value as parameter self.sliderBrightness.sliderReleased.connect( lambda: brUpdate(self.sliderBrightness.value())) # contrast slider self.sliderCont = QbLUeSlider(Qt.Horizontal) self.sliderCont.setStyleSheet( QbLUeSlider.bLueSliderDefaultBWStylesheet) self.sliderCont.setRange(0, 20) self.sliderCont.setSingleStep(1) self.contLabel = QLabel() self.contLabel.setText("Cont.") self.contValue = QLabel() font = self.contValue.font() metrics = QFontMetrics(font) w = metrics.width("100") h = metrics.height() self.contValue.setMinimumSize(w, h) self.contValue.setMaximumSize(w, h) self.contValue.setText( str("{:.0f}".format(self.slider2Cont(self.sliderCont.value())))) # cont done event handler def contUpdate(value): self.contValue.setText( str("{:.0f}".format(self.slider2Cont( self.sliderCont.value())))) # move not yet terminated or value not modified if self.sliderCont.isSliderDown() or self.slider2Cont( value) == self.tempCorrection: return try: self.sliderCont.valueChanged.disconnect() self.sliderCont.sliderReleased.disconnect() except RuntimeError: pass self.contCorrection = self.slider2Cont(self.sliderCont.value()) self.contValue.setText(str("{:+d}".format(self.contCorrection))) # force to recalculate the spline self.layer.autoSpline = True self.dataChanged.emit( 3) # no postprocessing and no camera profile stuff self.sliderCont.valueChanged.connect( contUpdate) # send new value as parameter self.sliderCont.sliderReleased.connect(lambda: contUpdate( self.sliderCont.value())) # signal has no parameter self.sliderCont.valueChanged.connect( contUpdate) # send new value as parameter self.sliderCont.sliderReleased.connect(lambda: contUpdate( self.sliderCont.value())) # signal has no parameter # saturation slider self.sliderSat = QbLUeSlider(Qt.Horizontal) self.sliderSat.setStyleSheet( QbLUeSlider.bLueSliderDefaultColorStylesheet) self.sliderSat.setRange(0, 100) self.sliderSat.setSingleStep(1) satLabel = QLabel() satLabel.setText("Sat.") self.satValue = QLabel() font = self.satValue.font() metrics = QFontMetrics(font) w = metrics.width("+10") h = metrics.height() self.satValue.setMinimumSize(w, h) self.satValue.setMaximumSize(w, h) self.satValue.setText( str("{:+d}".format(self.slider2Sat(self.sliderSat.value())))) """sat done event handler""" def satUpdate(value): self.satValue.setText( str("{:+d}".format(self.slider2Sat(self.sliderSat.value())))) # move not yet terminated or value not modified if self.sliderSat.isSliderDown() or self.slider2Sat( value) == self.satCorrection: return try: self.sliderSat.valueChanged.disconnect() self.sliderSat.sliderReleased.disconnect() except RuntimeError: pass self.satCorrection = self.slider2Sat(self.sliderSat.value()) self.dataChanged.emit( 3) # no post processing and no camera profile stuff self.sliderSat.valueChanged.connect( satUpdate) # send new value as parameter self.sliderSat.sliderReleased.connect(lambda: satUpdate( self.sliderSat.value())) # signal has no parameter self.sliderSat.valueChanged.connect( satUpdate) # send new value as parameter self.sliderSat.sliderReleased.connect(lambda: satUpdate( self.sliderSat.value())) # signal has no parameter # layout l = QVBoxLayout() l.addWidget(self.listWidget3) hl01 = QHBoxLayout() hl01.addWidget(QLabel('Camera Profile')) hl01.addWidget(self.cameraProfilesCombo) l.addLayout(hl01) hl0 = QHBoxLayout() hl0.addWidget(QLabel('Denoising')) hl0.addWidget(self.denoiseCombo) l.addLayout(hl0) hl00 = QHBoxLayout() hl00.addWidget(QLabel('Overexp. Restoration')) hl00.addWidget(self.overexpCombo) l.addLayout(hl00) hl1 = QHBoxLayout() hl1.addWidget(self.expLabel) hl1.addWidget(self.expValue) hl1.addWidget(self.sliderExp) l.addLayout(hl1) hl8 = QHBoxLayout() hl8.addWidget(brLabel) hl8.addWidget(self.brValue) hl8.addWidget(self.sliderBrightness) l.addLayout(hl8) l.addWidget(self.listWidget1) vl1 = QVBoxLayout() vl1.addWidget(self.listWidget2) gb1 = QGroupBox() gb1.setTitle('White Balance') hl2 = QHBoxLayout() hl2.addWidget(self.tempLabel) hl2.addWidget(self.tempValue) hl2.addWidget(self.sliderTemp) hl3 = QHBoxLayout() hl3.addWidget(self.tintLabel) hl3.addWidget(self.tintValue) hl3.addWidget(self.sliderTint) vl1.addLayout(hl2) vl1.addLayout(hl3) gb1.setLayout(vl1) l.addWidget(gb1) hl4 = QHBoxLayout() hl4.addWidget(self.contLabel) hl4.addWidget(self.contValue) hl4.addWidget(self.sliderCont) hl7 = QHBoxLayout() hl7.addWidget(satLabel) hl7.addWidget(self.satValue) hl7.addWidget(self.sliderSat) # separator sep = QFrame() sep.setFrameShape(QFrame.HLine) sep.setFrameShadow(QFrame.Sunken) l.addWidget(sep) l.addLayout(hl4) l.addLayout(hl7) l.addStretch(1) self.setLayout(l) self.adjustSize() self.setDefaults() self.setWhatsThis("""<b>Development of raw files</b><br> <b>Default settings</b> are a good starting point.<br> A <b>Tone Curve</b> is applied to the raw image prior to postprocessing.<br> The cuvre can be edited by checking the option <b>Show Tone Curve</b>; this option works best with manual exposure.<br> <b>Contrast</b> correction is based on an automatic algorithm well suited to multi-mode histograms.<br> <b>Brightness, Contrast</b> and <b>Saturation</b> levels</b> are adjustable with the correponding sliders.<br> The <b>Contrast Curve</b> can be edited manually by checking the option <b>Show Contrast Curve</b>.<br> Uncheck <b>Auto Expose</b> to adjust the exposure manually.<br> The <b>OverExp. Rest.</b> slider controls the mode of restoration of overexposed areas. Valid values are 0 to 3 (0=clip;1=unclip;2=blend;3=rebuild); (with Auto Exposed checked the mode is clip).<br> """) # end of setWhatsThis
def __init__(self, model, controller): super().__init__() self._model = model self._controller = controller self.segmentcursor = False self.togglecolors = {"#1f77b4": "m", "m": "#1f77b4"} ################################################################# # define GUI layout and connect input widgets to external slots # ################################################################# self.setWindowTitle("biopeaks") self.setGeometry(50, 50, 1750, 750) self.setWindowIcon(QIcon(":/python_icon.png")) # figure0 for signal self.figure0 = Figure() self.canvas0 = FigureCanvas(self.figure0) # Enforce minimum height, otherwise resizing with self.splitter causes # mpl to throw an error because figure is resized to height 0. The # widget can still be fully collapsed with self.splitter- self.canvas0.setMinimumHeight(1) # in pixels self.ax00 = self.figure0.add_subplot(1, 1, 1) self.ax00.set_frame_on(False) self.figure0.subplots_adjust(left=0.04, right=0.98, bottom=0.25) self.line00 = None self.scat = None self.segmentspan = None # figure1 for marker self.figure1 = Figure() self.canvas1 = FigureCanvas(self.figure1) self.canvas1.setMinimumHeight(1) self.ax10 = self.figure1.add_subplot(1, 1, 1, sharex=self.ax00) self.ax10.get_xaxis().set_visible(False) self.ax10.set_frame_on(False) self.figure1.subplots_adjust(left=0.04, right=0.98) self.line10 = None # figure2 for statistics self.figure2 = Figure() self.canvas2 = FigureCanvas(self.figure2) self.canvas2.setMinimumHeight(1) self.ax20 = self.figure2.add_subplot(3, 1, 1, sharex=self.ax00) self.ax20.get_xaxis().set_visible(False) self.ax20.set_frame_on(False) self.line20 = None self.ax21 = self.figure2.add_subplot(3, 1, 2, sharex=self.ax00) self.ax21.get_xaxis().set_visible(False) self.ax21.set_frame_on(False) self.line21 = None self.ax22 = self.figure2.add_subplot(3, 1, 3, sharex=self.ax00) self.ax22.get_xaxis().set_visible(False) self.ax22.set_frame_on(False) self.line22 = None self.figure2.subplots_adjust(left=0.04, right=0.98) # navigation bar self.navitools = CustomNavigationToolbar(self.canvas0, self) # peak editing self.editcheckbox = QCheckBox("editable", self) self.editcheckbox.stateChanged.connect(self._model.set_peakseditable) # peak saving batch self.savecheckbox = QCheckBox("save during batch processing", self) self.savecheckbox.stateChanged.connect(self._model.set_savebatchpeaks) # peak auto-correction batch self.correctcheckbox = QCheckBox("correct during batch processing", self) self.correctcheckbox.stateChanged.connect( self._model.set_correctbatchpeaks) # selecting stats for saving self.periodcheckbox = QCheckBox("period", self) self.periodcheckbox.stateChanged.connect( lambda: self.select_stats("period")) self.ratecheckbox = QCheckBox("rate", self) self.ratecheckbox.stateChanged.connect( lambda: self.select_stats("rate")) self.tidalampcheckbox = QCheckBox("tidal amplitude", self) self.tidalampcheckbox.stateChanged.connect( lambda: self.select_stats("tidalamp")) # channel selection self.sigchanmenulabel = QLabel("biosignal") self.sigchanmenu = QComboBox(self) self.sigchanmenu.addItem("A1") self.sigchanmenu.addItem("A2") self.sigchanmenu.addItem("A3") self.sigchanmenu.addItem("A4") self.sigchanmenu.addItem("A5") self.sigchanmenu.addItem("A6") self.sigchanmenu.currentTextChanged.connect(self._model.set_signalchan) # initialize with default value self._model.set_signalchan(self.sigchanmenu.currentText()) self.markerchanmenulabel = QLabel("marker") self.markerchanmenu = QComboBox(self) self.markerchanmenu.addItem("none") self.markerchanmenu.addItem("I1") self.markerchanmenu.addItem("I2") self.markerchanmenu.addItem("A1") self.markerchanmenu.addItem("A2") self.markerchanmenu.addItem("A3") self.markerchanmenu.addItem("A4") self.markerchanmenu.addItem("A5") self.markerchanmenu.addItem("A6") self.markerchanmenu.currentTextChanged.connect( self._model.set_markerchan) # initialize with default value self._model.set_markerchan(self.markerchanmenu.currentText()) # processing mode (batch or single file) self.batchmenulabel = QLabel("mode") self.batchmenu = QComboBox(self) self.batchmenu.addItem("single file") self.batchmenu.addItem("multiple files") self.batchmenu.currentTextChanged.connect(self._model.set_batchmode) self.batchmenu.currentTextChanged.connect(self.toggle_options) # initialize with default value self._model.set_batchmode(self.batchmenu.currentText()) self.toggle_options(self.batchmenu.currentText()) # modality selection self.modmenulabel = QLabel("modality") self.modmenu = QComboBox(self) self.modmenu.addItem("ECG") self.modmenu.addItem("PPG") self.modmenu.addItem("RESP") self.modmenu.currentTextChanged.connect(self._model.set_modality) self.modmenu.currentTextChanged.connect(self.toggle_options) # initialize with default value self._model.set_modality(self.modmenu.currentText()) self.toggle_options(self.modmenu.currentText()) # segment selection; this widget can be openend / set visible from # the menu and closed from within itself (see mapping of segmentermap); # it provides utilities to select a segment from the signal self.segmentermap = QSignalMapper(self) self.segmenter = QDockWidget("select a segment", self) # disable closing such that widget can only be closed by confirming # selection or custom button self.segmenter.setFeatures(QDockWidget.NoDockWidgetFeatures) # Limit number of decimals to four. regex = QRegExp("[0-9]*\.?[0-9]{4}") validator = QRegExpValidator(regex) self.startlabel = QLabel("start") self.startedit = QLineEdit() self.startedit.setValidator(validator) self.endlabel = QLabel("end") self.endedit = QLineEdit() self.endedit.setValidator(validator) segmentfromcursor = QAction(QIcon(":/mouse_icon.png"), "select with mouse", self) segmentfromcursor.triggered.connect(self.enable_segmentedit) self.startedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.endedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.previewedit = QPushButton("preview segment") lambdafn = lambda: self._model.set_segment( [self.startedit.text(), self.endedit.text()]) self.previewedit.clicked.connect(lambdafn) self.confirmedit = QPushButton("confirm segment") self.confirmedit.clicked.connect(self._controller.segment_signal) self.confirmedit.clicked.connect(self.segmentermap.map) self.segmentermap.setMapping(self.confirmedit, 0) self.abortedit = QPushButton("abort segmentation") self.abortedit.clicked.connect(self.segmentermap.map) # reset the segment to None self.segmentermap.setMapping(self.abortedit, 2) self.segmenterlayout = QFormLayout() self.segmenterlayout.addRow(self.startlabel, self.startedit) self.segmenterlayout.addRow(self.endlabel, self.endedit) self.segmenterlayout.addRow(self.previewedit) self.segmenterlayout.addRow(self.confirmedit) self.segmenterlayout.addRow(self.abortedit) self.segmenterwidget = QWidget() self.segmenterwidget.setLayout(self.segmenterlayout) self.segmenter.setWidget(self.segmenterwidget) self.segmenter.setVisible(False) self.segmenter.setAllowedAreas(Qt.RightDockWidgetArea) self.addDockWidget(Qt.RightDockWidgetArea, self.segmenter) # Set up dialog to gather user input for custom files. regex = QRegExp("[1-9][0-9]") validator = QRegExpValidator(regex) self.signallabel = QLabel("biosignal column") self.signaledit = QLineEdit() self.signaledit.setValidator(validator) self.markerlabel = QLabel("marker column") self.markeredit = QLineEdit() self.markeredit.setValidator(validator) regex = QRegExp("[0-9]{2}") validator = QRegExpValidator(regex) self.headerrowslabel = QLabel("number of header rows") self.headerrowsedit = QLineEdit() self.headerrowsedit.setValidator(validator) regex = QRegExp("[0-9]{5}") validator = QRegExpValidator(regex) self.sfreqlabel = QLabel("sampling rate") self.sfreqedit = QLineEdit() self.sfreqedit.setValidator(validator) self.separatorlabel = QLabel("column separator") self.separatormenu = QComboBox(self) self.separatormenu.addItem("comma") self.separatormenu.addItem("tab") self.separatormenu.addItem("colon") self.separatormenu.addItem("space") self.continuecustomfile = QPushButton("continue loading file") self.continuecustomfile.clicked.connect(self.set_customheader) self.customfiledialog = QDialog() self.customfiledialog.setWindowTitle("custom file info") self.customfiledialog.setWindowIcon(QIcon(":/file_icon.png")) self.customfiledialog.setWindowFlags( Qt.WindowCloseButtonHint ) # remove help button by only setting close button self.customfilelayout = QFormLayout() self.customfilelayout.addRow(self.signallabel, self.signaledit) self.customfilelayout.addRow(self.markerlabel, self.markeredit) self.customfilelayout.addRow(self.separatorlabel, self.separatormenu) self.customfilelayout.addRow(self.headerrowslabel, self.headerrowsedit) self.customfilelayout.addRow(self.sfreqlabel, self.sfreqedit) self.customfilelayout.addRow(self.continuecustomfile) self.customfiledialog.setLayout(self.customfilelayout) # set up menubar menubar = self.menuBar() # signal menu signalmenu = menubar.addMenu("biosignal") openSignal = signalmenu.addMenu("load") openEDF = QAction("EDF", self) openEDF.triggered.connect(lambda: self._model.set_filetype("EDF")) openEDF.triggered.connect(self._controller.get_fpaths) openSignal.addAction(openEDF) openOpenSignals = QAction("OpenSignals", self) openOpenSignals.triggered.connect( lambda: self._model.set_filetype("OpenSignals")) openOpenSignals.triggered.connect(self._controller.get_fpaths) openSignal.addAction(openOpenSignals) openCustom = QAction("Custom", self) openCustom.triggered.connect( lambda: self._model.set_filetype("Custom")) openCustom.triggered.connect(lambda: self.customfiledialog.exec_()) openSignal.addAction(openCustom) segmentSignal = QAction("select segment", self) segmentSignal.triggered.connect(self.segmentermap.map) self.segmentermap.setMapping(segmentSignal, 1) signalmenu.addAction(segmentSignal) self.segmentermap.mapped.connect(self.toggle_segmenter) saveSignal = QAction("save", self) saveSignal.triggered.connect(self._controller.get_wpathsignal) signalmenu.addAction(saveSignal) # peak menu peakmenu = menubar.addMenu("peaks") findPeaks = QAction("find", self) findPeaks.triggered.connect(self._controller.find_peaks) peakmenu.addAction(findPeaks) autocorrectPeaks = QAction("autocorrect", self) autocorrectPeaks.triggered.connect(self._controller.autocorrect_peaks) peakmenu.addAction(autocorrectPeaks) savePeaks = QAction("save", self) savePeaks.triggered.connect(self._controller.get_wpathpeaks) peakmenu.addAction(savePeaks) loadPeaks = QAction("load", self) loadPeaks.triggered.connect(self._controller.get_rpathpeaks) peakmenu.addAction(loadPeaks) # stats menu statsmenu = menubar.addMenu("statistics") calculateStats = QAction("calculate", self) calculateStats.triggered.connect(self._controller.calculate_stats) statsmenu.addAction(calculateStats) saveStats = QAction("save", self) saveStats.triggered.connect(self._controller.get_wpathstats) statsmenu.addAction(saveStats) # set up status bar to display error messages and current file path self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.progressBar = QProgressBar(self) self.progressBar.setRange(0, 1) self.statusBar.addPermanentWidget(self.progressBar) self.currentFile = QLabel() self.statusBar.addPermanentWidget(self.currentFile) # set up the central widget containing the plot and navigationtoolbar self.centwidget = QWidget() self.setCentralWidget(self.centwidget) # connect canvas0 to keyboard and mouse input for peak editing; # only widgets (e.g. canvas) that currently have focus capture # keyboard input: "You must enable keyboard focus for a widget if # it processes keyboard events." self.canvas0.setFocusPolicy(Qt.ClickFocus) self.canvas0.setFocus() self.canvas0.mpl_connect("key_press_event", self._controller.edit_peaks) self.canvas0.mpl_connect("button_press_event", self.get_xcursor) # arrange the three figure canvases in splitter object self.splitter = QSplitter(Qt.Vertical) # setting opaque resizing to false is important, since resizing gets # very slow otherwise once axes are populated self.splitter.setOpaqueResize(False) self.splitter.addWidget(self.canvas0) self.splitter.addWidget(self.canvas1) self.splitter.addWidget(self.canvas2) self.splitter.setChildrenCollapsible(False) # define GUI layout self.vlayout0 = QVBoxLayout(self.centwidget) self.vlayout1 = QVBoxLayout() self.vlayoutA = QFormLayout() self.vlayoutB = QFormLayout() self.vlayoutC = QVBoxLayout() self.vlayoutD = QVBoxLayout() self.hlayout0 = QHBoxLayout() self.optionsgroupA = QGroupBox("processing options") self.vlayoutA.addRow(self.modmenulabel, self.modmenu) self.vlayoutA.addRow(self.batchmenulabel, self.batchmenu) self.optionsgroupA.setLayout(self.vlayoutA) self.optionsgroupB = QGroupBox("channels") self.vlayoutB.addRow(self.sigchanmenulabel, self.sigchanmenu) self.vlayoutB.addRow(self.markerchanmenulabel, self.markerchanmenu) self.optionsgroupB.setLayout(self.vlayoutB) self.optionsgroupC = QGroupBox("peaks") self.vlayoutC.addWidget(self.editcheckbox) self.vlayoutC.addWidget(self.savecheckbox) self.vlayoutC.addWidget(self.correctcheckbox) self.optionsgroupC.setLayout(self.vlayoutC) self.optionsgroupD = QGroupBox("select statistics for saving") self.vlayoutD.addWidget(self.periodcheckbox) self.vlayoutD.addWidget(self.ratecheckbox) self.vlayoutD.addWidget(self.tidalampcheckbox) self.optionsgroupD.setLayout(self.vlayoutD) self.vlayout1.addWidget(self.optionsgroupA) self.vlayout1.addWidget(self.optionsgroupB) self.vlayout1.addWidget(self.optionsgroupC) self.vlayout1.addWidget(self.optionsgroupD) self.optionsgroupwidget = QWidget() self.optionsgroupwidget.setLayout(self.vlayout1) self.optionsgroup = QDockWidget("configurations", self) self.optionsgroup.setAllowedAreas(Qt.LeftDockWidgetArea) self.toggleoptionsgroup = self.optionsgroup.toggleViewAction() self.toggleoptionsgroup.setText("show/hide configurations") menubar.addAction(self.toggleoptionsgroup) self.optionsgroup.setWidget(self.optionsgroupwidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.optionsgroup) self.vlayout0.addWidget(self.splitter) self.hlayout0.addWidget(self.navitools) self.vlayout0.addLayout(self.hlayout0) ############################################## # connect output widgets to external signals # ############################################## self._model.signal_changed.connect(self.plot_signal) self._model.marker_changed.connect(self.plot_marker) self._model.peaks_changed.connect(self.plot_peaks) self._model.period_changed.connect(self.plot_period) self._model.rate_changed.connect(self.plot_rate) self._model.tidalamp_changed.connect(self.plot_tidalamp) self._model.path_changed.connect(self.display_path) self._model.segment_changed.connect(self.plot_segment) self._model.status_changed.connect(self.display_status) self._model.progress_changed.connect(self.display_progress) self._model.model_reset.connect(self.reset_plot)
def createGeneralTab(self): main_window = self.main_window # Masking options self.maskingCheck = QCheckBox('') self.maskingCheck.stateChanged.connect(main_window.toggleMasking) self.maskColorButton = QPushButton() self.maskColorButton.setCursor(QtCore.Qt.PointingHandCursor) self.maskColorButton.setFixedWidth( self.font_metric.width("XXXXXXXXXX")) self.maskColorButton.setFixedHeight(self.font_metric.height() * 1.5) self.maskColorButton.clicked.connect(main_window.editMaskingColor) # Highlighting options self.hlCheck = QCheckBox('') self.hlCheck.stateChanged.connect(main_window.toggleHighlighting) self.hlColorButton = QPushButton() self.hlColorButton.setCursor(QtCore.Qt.PointingHandCursor) self.hlColorButton.setFixedWidth(self.font_metric.width("XXXXXXXXXX")) self.hlColorButton.setFixedHeight(self.font_metric.height() * 1.5) self.hlColorButton.clicked.connect(main_window.editHighlightColor) self.alphaBox = QDoubleSpinBox() self.alphaBox.setRange(0, 1) self.alphaBox.setSingleStep(.05) self.alphaBox.valueChanged.connect(main_window.editAlpha) self.seedBox = QSpinBox() self.seedBox.setRange(1, 999) self.seedBox.valueChanged.connect(main_window.editSeed) # General options self.bgButton = QPushButton() self.bgButton.setCursor(QtCore.Qt.PointingHandCursor) self.bgButton.setFixedWidth(self.font_metric.width("XXXXXXXXXX")) self.bgButton.setFixedHeight(self.font_metric.height() * 1.5) self.bgButton.clicked.connect(main_window.editBackgroundColor) self.colorbyBox = QComboBox(self) self.colorbyBox.addItem("material") self.colorbyBox.addItem("cell") self.colorbyBox.addItem("temperature") self.colorbyBox.addItem("density") self.colorbyBox.currentTextChanged[str].connect( main_window.editColorBy) self.universeLevelBox = QComboBox(self) self.universeLevelBox.addItem('all') for i in range(self.model.max_universe_levels): self.universeLevelBox.addItem(str(i)) self.universeLevelBox.currentTextChanged[str].connect( main_window.editUniverseLevel) # Overlap plotting self.overlapCheck = QCheckBox('', self) overlap_connector = partial(main_window.toggleOverlaps) self.overlapCheck.stateChanged.connect(overlap_connector) self.overlapColorButton = QPushButton() self.overlapColorButton.setCursor(QtCore.Qt.PointingHandCursor) self.overlapColorButton.setFixedWidth( self.font_metric.width("XXXXXXXXXX")) self.overlapColorButton.setFixedHeight(self.font_metric.height() * 1.5) self.overlapColorButton.clicked.connect(main_window.editOverlapColor) self.colorResetButton = QPushButton("&Reset Colors") self.colorResetButton.setCursor(QtCore.Qt.PointingHandCursor) self.colorResetButton.clicked.connect(main_window.resetColors) formLayout = QFormLayout() formLayout.setAlignment(QtCore.Qt.AlignHCenter) formLayout.setFormAlignment(QtCore.Qt.AlignHCenter) formLayout.setLabelAlignment(QtCore.Qt.AlignLeft) formLayout.addRow('Masking:', self.maskingCheck) formLayout.addRow('Mask Color:', self.maskColorButton) formLayout.addRow(HorizontalLine()) formLayout.addRow('Highlighting:', self.hlCheck) formLayout.addRow('Highlight Color:', self.hlColorButton) formLayout.addRow('Highlight Alpha:', self.alphaBox) formLayout.addRow('Highlight Seed:', self.seedBox) formLayout.addRow(HorizontalLine()) formLayout.addRow('Background Color: ', self.bgButton) formLayout.addRow(HorizontalLine()) formLayout.addRow('Show Overlaps:', self.overlapCheck) formLayout.addRow('OVerlap Color:', self.overlapColorButton) formLayout.addRow(HorizontalLine()) formLayout.addRow('Color Plot By:', self.colorbyBox) formLayout.addRow('Universe Level:', self.universeLevelBox) formLayout.addRow(self.colorResetButton, None) generalLayout = QHBoxLayout() innerWidget = QWidget() generalLayout.setAlignment(QtCore.Qt.AlignVCenter) innerWidget.setLayout(formLayout) generalLayout.addStretch(1) generalLayout.addWidget(innerWidget) generalLayout.addStretch(1) self.generalTab = QWidget() self.generalTab.setLayout(generalLayout)
def __init__(self, parent: 'QMainWindow', gui: 'MetalGUI', components_to_render: list = None, soln_type: str = 'Eigenmode'): """ Get access to design, which has the components. Then set up the model and view. Args: parent (QMainWindow): The parent window gui (MetalGUI): The metal GUI components_to_render (list): A list of components to render to Ansys HFSS soln_type (str): Type of solution, either Eigenmode or Driven Modal """ super().__init__(parent) # Access design and Metal GUI: self._gui = gui # Use UI template from Qt Designer: self.ui = Ui_mainWindow() self.ui.setupUi(self) # Set up table widget for endcap list: self.table = self.ui.tableWidget self.components_to_render = components_to_render open_pins, shorted_pins = self.get_unconnected_pins( self.components_to_render) self.soln_type = soln_type if self.soln_type == 'Eigenmode': self.table.setColumnCount( 2) # Columns for pin name and endcap status endcap_options = ['Open', 'Shorted'] elif self.soln_type == 'Driven Modal': self.table.setColumnCount( 3 ) # Columns for pin name, endcap status, and impedance in Ohms endcap_options = ['Open', 'Shorted', 'Port'] self.pin_names = sorted(list(open_pins) + list(shorted_pins)) # sort alphabetically self.table.setRowCount(len(self.pin_names)) for idx in range(len(self.pin_names)): pin_name = QTableWidgetItem(', '.join(self.pin_names[idx])) self.table.setItem(idx, 0, pin_name) # pin name for first column endcap_combo = QComboBox() endcap_combo.addItems(endcap_options) self.table.setCellWidget( idx, 1, endcap_combo) # combobox for second column endcap_combo.setCurrentIndex( int(self.pin_names[idx] not in open_pins)) # default endcap type if self.soln_type == 'Driven Modal': impedance_value = QLineEdit() impedance_value.setText('50') self.table.setCellWidget(idx, 2, impedance_value) self.table.verticalHeader().setVisible(False) if self.soln_type == 'Eigenmode': self.table.setHorizontalHeaderLabels(['QComp, Pin', 'Endcap Type']) elif self.soln_type == 'Driven Modal': self.table.setHorizontalHeaderLabels( ['QComp, Pin', 'Endcap Type', 'Impedance (Ohms)']) self.table.horizontalHeader().setStretchLastSection(True)
def __init_geometry_widget__(self): self.__geometry_widget = QGroupBox("Geometry", self) load_geometry_button = QPushButton("Load Geometry") load_geometry_button.clicked.connect(self.load_geometry) remove_geometry_button = QPushButton("Remove Geometry") remove_geometry_button.clicked.connect(self.remove_geometry) rotate_x_label = QLabel("Rotate X:", self.__geometry_widget) self.rotate_x_slider = QSlider(orientation=Qt.Horizontal, parent=self.__geometry_widget) self.rotate_x_slider.setTickPosition(QSlider.TicksBothSides) self.rotate_x_slider.setTickInterval(45) self.rotate_x_slider.setRange(-180, 180) self.rotate_x_slider.setValue(0) self.rotate_x_spin = QSpinBox(self.__geometry_widget) self.rotate_x_spin.setMinimum(-180) self.rotate_x_spin.setMaximum(180) self.rotate_x_spin.setValue(0) self.rotate_x_slider.valueChanged.connect(self.rotate_x_spin.setValue) self.rotate_x_slider.valueChanged.connect( self.__slicer_widget.set_x_rotation) self.rotate_x_spin.valueChanged.connect(self.rotate_x_slider.setValue) self.rotate_x_spin.valueChanged.connect( self.__slicer_widget.set_x_rotation) rotate_y_label = QLabel("Rotate Y:", self.__geometry_widget) self.rotate_y_slider = QSlider(orientation=Qt.Horizontal, parent=self.__geometry_widget) self.rotate_y_slider.setTickPosition(QSlider.TicksBothSides) self.rotate_y_slider.setTickInterval(45) self.rotate_y_slider.setRange(-180, 180) self.rotate_y_slider.setValue(0) self.rotate_y_spin = QSpinBox(self.__geometry_widget) self.rotate_y_spin.setMinimum(-180) self.rotate_y_spin.setMaximum(180) self.rotate_y_spin.setValue(0) self.rotate_y_slider.valueChanged.connect(self.rotate_y_spin.setValue) self.rotate_y_slider.valueChanged.connect( self.__slicer_widget.set_y_rotation) self.rotate_y_spin.valueChanged.connect(self.rotate_y_slider.setValue) self.rotate_y_spin.valueChanged.connect( self.__slicer_widget.set_y_rotation) rotate_z_label = QLabel("Rotate Z:", self.__geometry_widget) self.rotate_z_slider = QSlider(orientation=Qt.Horizontal, parent=self.__geometry_widget) self.rotate_z_slider.setTickPosition(QSlider.TicksBothSides) self.rotate_z_slider.setTickInterval(45) self.rotate_z_slider.setRange(-180, 180) self.rotate_z_slider.setValue(0) self.rotate_z_spin = QSpinBox(self.__geometry_widget) self.rotate_z_spin.setMinimum(-180) self.rotate_z_spin.setMaximum(180) self.rotate_z_spin.setValue(0) self.rotate_z_slider.valueChanged.connect(self.rotate_z_spin.setValue) self.rotate_z_slider.valueChanged.connect( self.__slicer_widget.set_z_rotation) self.rotate_z_spin.valueChanged.connect(self.rotate_z_slider.setValue) self.rotate_z_spin.valueChanged.connect( self.__slicer_widget.set_z_rotation) translate_x_label = QLabel("Translate X:", self.__geometry_widget) self.translate_x_slider = QSlider(orientation=Qt.Horizontal, parent=self.__geometry_widget) self.translate_x_slider.setTickPosition(QSlider.TicksBothSides) self.translate_x_slider.setTickInterval( self.dlp_controller.projector_pixel_size) self.translate_x_slider.setRange( -self.dlp_controller.projector_width * self.dlp_controller.projector_pixel_size * 0.5, self.dlp_controller.projector_width * self.dlp_controller.projector_pixel_size * 0.5) self.translate_x_slider.setValue(0) self.translate_x_spin = QDoubleSpinBox(self.__geometry_widget) self.translate_x_spin.setMinimum( -self.dlp_controller.projector_width * self.dlp_controller.projector_pixel_size * 0.5) self.translate_x_spin.setMaximum( self.dlp_controller.projector_width * self.dlp_controller.projector_pixel_size * 0.5) self.translate_x_spin.setSingleStep( self.dlp_controller.projector_pixel_size) self.translate_x_spin.setValue(0) self.translate_x_slider.valueChanged.connect( self.translate_x_spin.setValue) self.translate_x_slider.valueChanged.connect( self.__slicer_widget.set_x_pos) self.translate_x_spin.valueChanged.connect( self.translate_x_slider.setValue) self.translate_x_spin.valueChanged.connect( self.__slicer_widget.set_x_pos) translate_z_label = QLabel("Translate Z:", self.__geometry_widget) self.translate_z_slider = QSlider(orientation=Qt.Horizontal, parent=self.__geometry_widget) self.translate_z_slider.setTickPosition(QSlider.TicksBothSides) self.translate_z_slider.setTickInterval( self.dlp_controller.projector_pixel_size) self.translate_z_slider.setRange( -self.dlp_controller.projector_height * self.dlp_controller.projector_pixel_size * 0.5, self.dlp_controller.projector_height * self.dlp_controller.projector_pixel_size * 0.5) self.translate_z_slider.setValue(0) self.translate_z_spin = QDoubleSpinBox(self.__geometry_widget) self.translate_z_spin.setMinimum( -self.dlp_controller.projector_height * self.dlp_controller.projector_pixel_size * 0.5) self.translate_z_spin.setMaximum( self.dlp_controller.projector_height * self.dlp_controller.projector_pixel_size * 0.5) self.translate_z_spin.setSingleStep( self.dlp_controller.projector_pixel_size) self.translate_z_spin.setValue(0) self.translate_z_slider.valueChanged.connect( self.translate_z_spin.setValue) self.translate_z_slider.valueChanged.connect( self.__slicer_widget.set_z_pos) self.translate_z_spin.valueChanged.connect( self.translate_z_slider.setValue) self.translate_z_spin.valueChanged.connect( self.__slicer_widget.set_z_pos) scale_x_label = QLabel("Scale X:", self.__geometry_widget) self.scale_x_spin = QDoubleSpinBox(self.__geometry_widget) self.scale_x_spin.setMinimum(-1000) self.scale_x_spin.setMaximum(1000) self.scale_x_spin.setDecimals(2) self.scale_x_spin.setValue(1) self.scale_x_spin.setSingleStep(0.01) self.scale_x_spin.setObjectName("scale_x_spin") self.scale_x_spin.valueChanged.connect(self.set_scaling) scale_y_label = QLabel("Scale Y:", self.__geometry_widget) self.scale_y_spin = QDoubleSpinBox(self.__geometry_widget) self.scale_y_spin.setMinimum(-1000) self.scale_y_spin.setMaximum(1000) self.scale_y_spin.setDecimals(2) self.scale_y_spin.setValue(1) self.scale_y_spin.setSingleStep(0.01) self.scale_y_spin.setObjectName("scale_y_spin") self.scale_y_spin.valueChanged.connect(self.set_scaling) scale_z_label = QLabel("Scale Z:", self.__geometry_widget) self.scale_z_spin = QDoubleSpinBox(self.__geometry_widget) self.scale_z_spin.setMinimum(-1000) self.scale_z_spin.setMaximum(1000) self.scale_z_spin.setDecimals(2) self.scale_z_spin.setValue(1) self.scale_z_spin.setSingleStep(0.01) self.scale_z_spin.setObjectName("scale_z_spin") self.scale_z_spin.valueChanged.connect(self.set_scaling) self.uniform_scaling = QCheckBox("Uniform Scaling", self.__geometry_widget) self.uniform_scaling.setChecked(True) # self.uniform_scaling.setLayoutDirection(Qt.RightToLeft) list_of_measures = ('\u03BCm', 'mm', 'cm', 'dm', 'm') self.list_of_measures_coefficients = [0.001, 1, 10, 100, 1000] unit_of_measure_label = QLabel("Unit of Measure", self.__geometry_widget) self.unit_of_measure_combo = QComboBox(self.__geometry_widget) for measure in list_of_measures: self.unit_of_measure_combo.addItem(measure) self.unit_of_measure_combo.setCurrentIndex(1) self.unit_of_measure_combo.currentIndexChanged.connect( self.update_unit_of_measure) rotate_x_row = 0 rotate_y_row = rotate_x_row + 1 rotate_z_row = rotate_y_row + 1 translate_x_row = rotate_z_row + 1 translate_z_row = translate_x_row + 1 scale_x_row = translate_z_row + 1 scale_y_row = scale_x_row + 1 scale_z_row = scale_y_row + 1 uniform_scaling_row = scale_x_row unit_of_measure_row = scale_y_row load_geometry_row = scale_z_row + 1 remove_geometry_row = load_geometry_row geometry_layout = QGridLayout(self.__geometry_widget) geometry_layout.addWidget(load_geometry_button, load_geometry_row, 1, 1, 2) geometry_layout.addWidget(remove_geometry_button, remove_geometry_row, 3, 1, 2) geometry_layout.addWidget(rotate_x_label, rotate_x_row, 0) geometry_layout.addWidget(self.rotate_x_slider, rotate_x_row, 1, 1, 4) geometry_layout.addWidget(self.rotate_x_spin, rotate_x_row, 5) geometry_layout.addWidget(rotate_y_label, rotate_y_row, 0) geometry_layout.addWidget(self.rotate_y_slider, rotate_y_row, 1, 1, 4) geometry_layout.addWidget(self.rotate_y_spin, rotate_y_row, 5) geometry_layout.addWidget(rotate_z_label, rotate_z_row, 0) geometry_layout.addWidget(self.rotate_z_slider, rotate_z_row, 1, 1, 4) geometry_layout.addWidget(self.rotate_z_spin, rotate_z_row, 5) geometry_layout.addWidget(translate_x_label, translate_x_row, 0) geometry_layout.addWidget(self.translate_x_slider, translate_x_row, 1, 1, 4) geometry_layout.addWidget(self.translate_x_spin, translate_x_row, 5) geometry_layout.addWidget(translate_z_label, translate_z_row, 0) geometry_layout.addWidget(self.translate_z_slider, translate_z_row, 1, 1, 4) geometry_layout.addWidget(self.translate_z_spin, translate_z_row, 5) geometry_layout.addWidget(scale_x_label, scale_x_row, 0) geometry_layout.addWidget(self.scale_x_spin, scale_x_row, 1) geometry_layout.addWidget(scale_y_label, scale_y_row, 0) geometry_layout.addWidget(self.scale_y_spin, scale_y_row, 1) geometry_layout.addWidget(scale_z_label, scale_z_row, 0) geometry_layout.addWidget(self.scale_z_spin, scale_z_row, 1) geometry_layout.addWidget(self.uniform_scaling, uniform_scaling_row, 3, 1, 2) geometry_layout.addWidget(unit_of_measure_label, unit_of_measure_row, 4) geometry_layout.addWidget(self.unit_of_measure_combo, unit_of_measure_row, 3) self.__geometry_widget.setLayout(geometry_layout)
def __init__( self, parent, ground_object: TheaterGroundObject, cp: ControlPoint, game: Game, current_group_value: int, ): super(QBuyGroupForGroundObjectDialog, self).__init__(parent) self.setMinimumWidth(350) self.ground_object = ground_object self.cp = cp self.game = game self.current_group_value = current_group_value self.setWindowTitle("Buy units @ " + self.ground_object.obj_name) self.setWindowIcon(EVENT_ICONS["capture"]) self.buySamButton = QPushButton("Buy") self.buyArmorButton = QPushButton("Buy") self.buySamLayout = QGridLayout() self.buyArmorLayout = QGridLayout() self.amount = QSpinBox() self.buyArmorCombo = QComboBox() self.samCombo = QComboBox() self.buySamBox = QGroupBox("Buy SAM site :") self.buyArmorBox = QGroupBox("Buy defensive position :") faction = self.game.player_faction # Sams possible_sams = get_faction_possible_sams_generator(faction) for sam in possible_sams: # Pre Generate SAM to get the real price generator = sam(self.game, self.ground_object) generator.generate() self.samCombo.addItem( generator.name + " [$" + str(generator.price) + "M]", userData=generator ) self.samCombo.currentIndexChanged.connect(self.samComboChanged) self.buySamLayout.addWidget(QLabel("Site Type :"), 0, 0, Qt.AlignLeft) self.buySamLayout.addWidget(self.samCombo, 0, 1, alignment=Qt.AlignRight) self.buySamLayout.addWidget(self.buySamButton, 1, 1, alignment=Qt.AlignRight) stretch = QVBoxLayout() stretch.addStretch() self.buySamLayout.addLayout(stretch, 2, 0) self.buySamButton.clicked.connect(self.buySam) # EWRs buy_ewr_box = QGroupBox("Buy EWR:") buy_ewr_layout = QGridLayout() buy_ewr_box.setLayout(buy_ewr_layout) buy_ewr_layout.addWidget(QLabel("Radar type:"), 0, 0, Qt.AlignLeft) self.ewr_selector = QComboBox() buy_ewr_layout.addWidget(self.ewr_selector, 0, 1, alignment=Qt.AlignRight) ewr_types = get_faction_possible_ewrs_generator(faction) for ewr_type in ewr_types: # Pre Generate to get the real price generator = ewr_type(self.game, self.ground_object) generator.generate() self.ewr_selector.addItem( generator.name() + " [$" + str(generator.price) + "M]", userData=generator, ) self.ewr_selector.currentIndexChanged.connect(self.on_ewr_selection_changed) self.buy_ewr_button = QPushButton("Buy") self.buy_ewr_button.clicked.connect(self.buy_ewr) buy_ewr_layout.addWidget(self.buy_ewr_button, 1, 1, alignment=Qt.AlignRight) stretch = QVBoxLayout() stretch.addStretch() buy_ewr_layout.addLayout(stretch, 2, 0) # Armored units for unit in set(faction.ground_units): self.buyArmorCombo.addItem(f"{unit} [${unit.price}M]", userData=unit) self.buyArmorCombo.currentIndexChanged.connect(self.armorComboChanged) self.amount.setMinimum(2) self.amount.setMaximum(8) self.amount.setValue(2) self.amount.valueChanged.connect(self.amountComboChanged) self.buyArmorLayout.addWidget(QLabel("Unit type :"), 0, 0, Qt.AlignLeft) self.buyArmorLayout.addWidget(self.buyArmorCombo, 0, 1, alignment=Qt.AlignRight) self.buyArmorLayout.addWidget( QLabel("Group size :"), 1, 0, alignment=Qt.AlignLeft ) self.buyArmorLayout.addWidget(self.amount, 1, 1, alignment=Qt.AlignRight) self.buyArmorLayout.addWidget( self.buyArmorButton, 2, 1, alignment=Qt.AlignRight ) stretch2 = QVBoxLayout() stretch2.addStretch() self.buyArmorLayout.addLayout(stretch2, 3, 0) self.buyArmorButton.clicked.connect(self.buyArmor) # Do layout self.buySamBox.setLayout(self.buySamLayout) self.buyArmorBox.setLayout(self.buyArmorLayout) self.mainLayout = QHBoxLayout() if isinstance(self.ground_object, SamGroundObject): self.mainLayout.addWidget(self.buySamBox) elif isinstance(self.ground_object, VehicleGroupGroundObject): self.mainLayout.addWidget(self.buyArmorBox) elif isinstance(self.ground_object, EwrGroundObject): self.mainLayout.addWidget(buy_ewr_box) self.setLayout(self.mainLayout) try: self.samComboChanged(0) self.armorComboChanged(0) self.on_ewr_selection_changed(0) except: pass
def __init__(self, sensor_controller: SensorController): super().__init__() self.sensor_controller = sensor_controller layout = QGridLayout() self.setLayout(layout) self.setMaximumHeight(400) # simulate select_sensor_group = QGroupBox() simulate_layout = QGridLayout() select_sensor_group.setLayout(simulate_layout) simulate_label = QLabel('Simulate') self.simulate_checkbox = QCheckBox() sensor_port_label = QLabel('Sensor COM') self.sensor_port_input = QComboBox() self.sensor_port_input.setEditable(True) amplitude_scale_label = QLabel('Scale') self.amplitude_scale_input = QLineEdit() self.amplitude_scale_input.setValidator(QDoubleValidator(0.0, 1.0, 10)) simulate_layout.addWidget(simulate_label, 0, 0) simulate_layout.addWidget(self.simulate_checkbox, 0, 1) simulate_layout.addWidget(sensor_port_label, 1, 0) simulate_layout.addWidget(self.sensor_port_input, 1, 1) simulate_layout.addWidget(amplitude_scale_label, 2, 0) simulate_layout.addWidget(self.amplitude_scale_input, 2, 1) layout.addWidget(select_sensor_group, 0, 0, 1, 2) # bandpass bandpass_group = QGroupBox() bandpass_layout = QGridLayout() bandpass_group.setLayout(bandpass_layout) bandpass_label = QLabel('Bandpass') bandpass_checkbox = QCheckBox() bp_high_label = QLabel('High, Hz') bp_high_input = QLineEdit() bp_low_label = QLabel('Low, Hz') bp_low_input = QLineEdit() bandpass_layout.addWidget(bandpass_label, 0, 0) bandpass_layout.addWidget(bandpass_checkbox, 0, 1) bandpass_layout.addWidget(bp_high_label, 1, 0) bandpass_layout.addWidget(bp_high_input, 1, 1) bandpass_layout.addWidget(bp_low_label, 2, 0) bandpass_layout.addWidget(bp_low_input, 2, 1) layout.addWidget(bandpass_group, 1, 0, 1, 2) # notch notch_group = QGroupBox() notch_layout = QGridLayout() notch_group.setLayout(notch_layout) notch_label = QLabel('Notch') notch_checkbox = QCheckBox() notch_input_label = QLabel('Notch, Hz') notch_input = QLineEdit() notch_layout.addWidget(notch_label, 0, 0) notch_layout.addWidget(notch_checkbox, 0, 1) notch_layout.addWidget(notch_input_label, 1, 0) notch_layout.addWidget(notch_input, 1, 1) layout.addWidget(notch_group, 2, 0, 1, 2) # start/stop btn_start = QPushButton("Start data") btn_stop = QPushButton("Stop data") btn_start.clicked.connect(sensor_controller.start_data) btn_stop.clicked.connect(sensor_controller.stop_data) layout.addWidget(btn_start, 3, 0) layout.addWidget(btn_stop, 3, 1) self.bind_controls() self.sensor_controller.rx_sensor_settings_subject.subscribe(self.draw_sensor_settings)
def __init__(self, *args, **kwargs): super(ExportFileDialog, self).__init__(*args, **kwargs) self.mainWindow = self.parent() self.setWindowTitle("Export nodes to CSV") self.setAcceptMode(QFileDialog.AcceptSave) self.setOption(QFileDialog.DontUseNativeDialog) #self.setFilter("CSV Files (*.csv)") self.setDefaultSuffix("csv") self.optionBOM = QCheckBox("Use a BOM", self) self.optionBOM.setCheckState(Qt.CheckState.Checked) self.optionLinebreaks = QCheckBox("Remove line breaks", self) self.optionLinebreaks.setCheckState(Qt.CheckState.Checked) self.optionSeparator = QComboBox(self) self.optionSeparator.insertItems(0, [";", "\\t", ","]) self.optionSeparator.setEditable(True) #self.optionLinebreaks.setCheckState(Qt.CheckState.Checked) self.optionWide = QCheckBox( "Convert to wide format (experimental feature)", self) self.optionWide.setCheckState(Qt.CheckState.Unchecked) # if none or all are selected, export all # if one or more are selected, export selective self.optionAll = QComboBox(self) self.optionAll.insertItems(0, [ 'All nodes (faster for large datasets, ordered by internal ID)', 'Selected nodes (ordered like shown in nodes view)' ]) if self.mainWindow.tree.noneOrAllSelected(): self.optionAll.setCurrentIndex(0) else: self.optionAll.setCurrentIndex(1) layout = self.layout() row = layout.rowCount() layout.addWidget(QLabel('Options'), row, 0) options = QHBoxLayout() options.addWidget(self.optionBOM) options.addWidget(self.optionLinebreaks) options.addWidget(QLabel('Separator')) options.addWidget(self.optionSeparator) options.addStretch(1) layout.addLayout(options, row, 1, 1, 2) layout.addWidget(QLabel('Post processing'), row + 1, 0) layout.addWidget(self.optionWide, row + 1, 1, 1, 2) layout.addWidget(QLabel('Export mode'), row + 2, 0) layout.addWidget(self.optionAll, row + 2, 1, 1, 2) self.setLayout(layout) if self.exec_(): if os.path.isfile(self.selectedFiles()[0]): os.remove(self.selectedFiles()[0]) output = open(self.selectedFiles()[0], 'w', newline='', encoding='utf8') if self.optionBOM.isChecked() and not self.optionWide.isChecked(): output.write('\ufeff') try: if self.optionAll.currentIndex() == 0: self.exportAllNodes(output) else: self.exportSelectedNodes(output) finally: output.close() if self.optionWide.isChecked(): self.convertToWideFormat(self.selectedFiles()[0])
def init_ui(self): self.hbox = QHBoxLayout() # holds widgets for refresh button, desired address, and size to grab self.vbox = QVBoxLayout() # main container self.lower_hbox = QSplitter() # holds memory views self.lower_container = QHBoxLayout() # holds lower_hbox and the endian_vbox self.endian_vbox = QVBoxLayout() self.hbox.addWidget(QLabel('Address:')) self.address = QLineEdit() self.hbox.addWidget(self.address) self.hbox.addWidget(QLabel('Size:')) self.size = QLineEdit() self.hbox.addWidget(self.size) self.hbox.addWidget(QLabel('Grouping:')) self.grouping = QComboBox() self.grouping.addItems(['1','2','4','8']) self.hbox.addWidget(self.grouping) self.search = QPushButton('Search') self.search.clicked.connect(lambda:self.find(self.address.text(), constants['block_size'])) self.hbox.addWidget(self.search) self.refresh = QPushButton('Refresh') self.refresh.clicked.connect(lambda:self.grab_data(val=self.address.text(), size=self.size.text(), grouping=self.grouping.currentText(), refresh=True)) self.hbox.addWidget(self.refresh) self.save = QPushButton('Save') self.save.clicked.connect(lambda: self.save_to_file()) self.disable_save(self.qmp.running) self.qmp.stateChanged.connect(self.disable_save) self.hbox.addWidget(self.save) self.auto_refresh = QCheckBox('Auto Refresh') self.auto_refresh.setCheckState(Qt.CheckState.Checked) self.auto_refresh.stateChanged.connect(self.auto_refresh_check) self.hbox.addWidget(self.auto_refresh) self.vbox.addLayout(self.hbox) # textbox for addresses self.addresses = QTextEdit() self.addresses.setReadOnly(True) self.addresses.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.addresses.setLineWrapMode(QTextEdit.NoWrap) self.addresses.setCurrentFont(QFont('Courier New')) self.addresses.setGeometry(0,0,150,500) self.lower_hbox.addWidget(self.addresses) # textbox for hex display of memory self.mem_display = QTextEdit() self.mem_display.setReadOnly(True) self.mem_display.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.mem_display.setLineWrapMode(QTextEdit.NoWrap) self.mem_display.setCurrentFont(QFont('Courier New')) self.mem_display.setGeometry(0,0,600,500) self.lower_hbox.addWidget(self.mem_display) # textbox for char display of memory self.chr_display = QTextEdit() self.chr_display.setReadOnly(True) self.chr_display.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.chr_display.setLineWrapMode(QTextEdit.NoWrap) self.chr_display.setCurrentFont(QFont('Courier New')) self.mem_display.setGeometry(0,0,400,500) self.lower_hbox.addWidget(self.chr_display) self.lower_container.addWidget(self.lower_hbox) self.mem_display.verticalScrollBar().valueChanged.connect(self.addresses.verticalScrollBar().setValue) #synchronizes addresses's scroll bar to mem_display's self.addresses.verticalScrollBar().valueChanged.connect(self.mem_display.verticalScrollBar().setValue) #synchronizes mem_display's scroll to addresses's, allowing for searching for addresses to scrol mem_display to the desired point self.chr_display.verticalScrollBar().valueChanged.connect(self.mem_display.verticalScrollBar().setValue) self.mem_display.verticalScrollBar().valueChanged.connect(self.chr_display.verticalScrollBar().setValue) self.chr_display.verticalScrollBar().valueChanged.connect(self.handle_scroll) # allows us to do scrolling # setting up endiannes selection buttons self.little = QRadioButton("Little Endian") self.little.click() self.little.clicked.connect(lambda:self.change_endian(Endian.little)) self.big = QRadioButton("Big Endian") self.big.clicked.connect(lambda:self.change_endian(Endian.big)) self.endian_vbox.addWidget(self.little) self.endian_vbox.addWidget(self.big) self.endian_vbox.addSpacing(400) self.lower_container.addLayout(self.endian_vbox) self.vbox.addLayout(self.lower_container) self.vbox.setSpacing(10) self.setLayout(self.vbox) self.setWindowTitle("Memory Dump") self.setGeometry(100, 100, 1550, 500)
def _create_dock_windows(self): """Create dock windows and connects them to gui.""" def _make_dock(name, widgets=[], tab_with=None): dock = QDockWidget(name) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) dock_widget = QWidget() layout = QVBoxLayout() for widget in widgets: layout.addWidget(widget) dock_widget.setLayout(layout) dock.setWidget(dock_widget) key = f"hide {name.lower()} dock" if key in prefs and prefs[key]: dock.hide() self.addDockWidget(Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) if tab_with is not None: self.tabifyDockWidget(tab_with, dock) return layout def _add_button(to, label, action, key=None): key = key or label.lower() btn = QPushButton(label) btn.clicked.connect(action) to.addWidget(btn) self._buttons[key] = btn return btn ####### Videos ####### videos_layout = _make_dock("Videos") self.videosTable = GenericTableView( state=self.state, row_name="video", is_activatable=True, model=VideosTableModel(items=self.labels.videos, context=self.commands), ) videos_layout.addWidget(self.videosTable) hb = QHBoxLayout() _add_button(hb, "Show Video", self.videosTable.activateSelected) _add_button(hb, "Add Videos", self.commands.addVideo) _add_button(hb, "Remove Video", self.commands.removeVideo) hbw = QWidget() hbw.setLayout(hb) videos_layout.addWidget(hbw) ####### Skeleton ####### skeleton_layout = _make_dock("Skeleton", tab_with=videos_layout.parent().parent()) gb = QGroupBox("Nodes") vb = QVBoxLayout() self.skeletonNodesTable = GenericTableView( state=self.state, row_name="node", model=SkeletonNodesTableModel(items=self.state["skeleton"], context=self.commands), ) vb.addWidget(self.skeletonNodesTable) hb = QHBoxLayout() _add_button(hb, "New Node", self.commands.newNode) _add_button(hb, "Delete Node", self.commands.deleteNode) hbw = QWidget() hbw.setLayout(hb) vb.addWidget(hbw) gb.setLayout(vb) skeleton_layout.addWidget(gb) def _update_edge_src(): self.skeletonEdgesDst.model().skeleton = self.state["skeleton"] gb = QGroupBox("Edges") vb = QVBoxLayout() self.skeletonEdgesTable = GenericTableView( state=self.state, row_name="edge", model=SkeletonEdgesTableModel(items=self.state["skeleton"], context=self.commands), ) vb.addWidget(self.skeletonEdgesTable) hb = QHBoxLayout() self.skeletonEdgesSrc = QComboBox() self.skeletonEdgesSrc.setEditable(False) self.skeletonEdgesSrc.currentIndexChanged.connect(_update_edge_src) self.skeletonEdgesSrc.setModel( SkeletonNodeModel(self.state["skeleton"])) hb.addWidget(self.skeletonEdgesSrc) hb.addWidget(QLabel("to")) self.skeletonEdgesDst = QComboBox() self.skeletonEdgesDst.setEditable(False) hb.addWidget(self.skeletonEdgesDst) self.skeletonEdgesDst.setModel( SkeletonNodeModel(self.state["skeleton"], lambda: self.skeletonEdgesSrc.currentText())) def new_edge(): src_node = self.skeletonEdgesSrc.currentText() dst_node = self.skeletonEdgesDst.currentText() self.commands.newEdge(src_node, dst_node) _add_button(hb, "Add Edge", new_edge) _add_button(hb, "Delete Edge", self.commands.deleteEdge) hbw = QWidget() hbw.setLayout(hb) vb.addWidget(hbw) gb.setLayout(vb) skeleton_layout.addWidget(gb) hb = QHBoxLayout() _add_button(hb, "Load Skeleton", self.commands.openSkeleton) _add_button(hb, "Save Skeleton", self.commands.saveSkeleton) hbw = QWidget() hbw.setLayout(hb) skeleton_layout.addWidget(hbw) ####### Instances ####### instances_layout = _make_dock("Instances") self.instancesTable = GenericTableView( state=self.state, row_name="instance", name_prefix="", model=LabeledFrameTableModel(items=self.state["labeled_frame"], context=self.commands), ) instances_layout.addWidget(self.instancesTable) hb = QHBoxLayout() _add_button(hb, "New Instance", lambda x: self.commands.newInstance()) _add_button(hb, "Delete Instance", self.commands.deleteSelectedInstance) hbw = QWidget() hbw.setLayout(hb) instances_layout.addWidget(hbw) ####### Suggestions ####### suggestions_layout = _make_dock("Labeling Suggestions") self.suggestionsTable = GenericTableView( state=self.state, is_sortable=True, model=SuggestionsTableModel(items=self.labels.suggestions, context=self.commands), ) suggestions_layout.addWidget(self.suggestionsTable) hb = QHBoxLayout() _add_button( hb, "Prev", self.process_events_then(self.commands.prevSuggestedFrame), "goto previous suggestion", ) self.suggested_count_label = QLabel() hb.addWidget(self.suggested_count_label) _add_button( hb, "Next", self.process_events_then(self.commands.nextSuggestedFrame), "goto next suggestion", ) hbw = QWidget() hbw.setLayout(hb) suggestions_layout.addWidget(hbw) self.suggestions_form_widget = YamlFormWidget.from_name( "suggestions", title="Generate Suggestions", ) self.suggestions_form_widget.mainAction.connect( self.process_events_then(self.commands.generateSuggestions)) suggestions_layout.addWidget(self.suggestions_form_widget) def goto_suggestion(*args): selected_frame = self.suggestionsTable.getSelectedRowItem() self.commands.gotoVideoAndFrame(selected_frame.video, selected_frame.frame_idx) self.suggestionsTable.doubleClicked.connect(goto_suggestion) self.state.connect("suggestion_idx", self.suggestionsTable.selectRow)
def init_ui(self): self.setWindowTitle(self.tr("Dataset Viewer")) self.data_table = QTableWidget(100, 100) self.data_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.data_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.data_table.setAlternatingRowColors(True) self.data_table.setContextMenuPolicy(Qt.CustomContextMenu) # self.data_table.hideColumn(0) self.main_layout = QGridLayout(self) self.main_layout.addWidget(self.data_table, 0, 0, 1, 3) self.previous_button = QPushButton(self.tr("Previous")) self.previous_button.setToolTip( self.tr("Click to back to the previous page.")) self.previous_button.clicked.connect(self.on_previous_button_clicked) self.current_page_combo_box = QComboBox() self.current_page_combo_box.currentIndexChanged.connect( self.update_page) self.next_button = QPushButton(self.tr("Next")) self.next_button.setToolTip(self.tr("Click to jump to the next page.")) self.next_button.clicked.connect(self.on_next_button_clicked) self.main_layout.addWidget(self.previous_button, 1, 0) self.main_layout.addWidget(self.current_page_combo_box, 1, 1) self.main_layout.addWidget(self.next_button, 1, 2) self.geometric_checkbox = QCheckBox(self.tr("Geometric")) self.geometric_checkbox.setChecked(True) self.geometric_checkbox.stateChanged.connect( self.on_is_geometric_changed) self.main_layout.addWidget(self.geometric_checkbox, 2, 0) self.FW57_checkbox = QCheckBox(self.tr("Method of statistic moments")) self.FW57_checkbox.setChecked(False) self.FW57_checkbox.stateChanged.connect(self.on_is_FW57_changed) self.main_layout.addWidget(self.FW57_checkbox, 2, 1) self.proportion_combo_box = QComboBox() self.supported_proportions = [ ("GSM_proportion", self.tr("Gravel, Sand, Mud")), ("SSC_proportion", self.tr("Sand, Silt, Clay")), ("BGSSC_proportion", self.tr("Boulder, Gravel, Sand, Silt, Clay")) ] self.proportion_combo_box.addItems( [description for _, description in self.supported_proportions]) self.proportion_combo_box.currentIndexChanged.connect( lambda: self.update_page(self.page_index)) self.main_layout.addWidget(self.proportion_combo_box, 2, 2) self.menu = QMenu(self.data_table) self.load_dataset_action = self.menu.addAction(qta.icon("fa.database"), self.tr("Load Dataset")) self.load_dataset_action.triggered.connect(self.load_dataset) self.plot_cumulative_curve_menu = self.menu.addMenu( qta.icon("mdi.chart-bell-curve-cumulative"), self.tr("Plot Cumlulative Curve Chart")) self.cumulative_plot_selected_action = self.plot_cumulative_curve_menu.addAction( self.tr("Plot Selected Samples")) self.cumulative_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.cumulative_curve_chart, self. selections, False)) self.cumulative_append_selected_action = self.plot_cumulative_curve_menu.addAction( self.tr("Append Selected Samples")) self.cumulative_append_selected_action.triggered.connect( lambda: self.plot_chart(self.cumulative_curve_chart, self. selections, True)) self.cumulative_plot_all_action = self.plot_cumulative_curve_menu.addAction( self.tr("Plot All Samples")) self.cumulative_plot_all_action.triggered.connect( lambda: self.plot_chart(self.cumulative_curve_chart, self.__dataset .samples, False)) self.cumulative_append_all_action = self.plot_cumulative_curve_menu.addAction( self.tr("Append All Samples")) self.cumulative_append_all_action.triggered.connect( lambda: self.plot_chart(self.cumulative_curve_chart, self.__dataset .samples, True)) self.plot_frequency_curve_menu = self.menu.addMenu( qta.icon("mdi.chart-bell-curve"), self.tr("Plot Frequency Curve Chart")) self.frequency_plot_selected_action = self.plot_frequency_curve_menu.addAction( self.tr("Plot Selected Samples")) self.frequency_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_chart, self. selections, False)) self.frequency_append_selected_action = self.plot_frequency_curve_menu.addAction( self.tr("Append Selected Samples")) self.frequency_append_selected_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_chart, self. selections, True)) self.frequency_plot_all_action = self.plot_frequency_curve_menu.addAction( self.tr("Plot All Samples")) self.frequency_plot_all_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_chart, self.__dataset. samples, False)) self.frequency_append_all_action = self.plot_frequency_curve_menu.addAction( self.tr("Append All Samples")) self.frequency_append_all_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_chart, self.__dataset. samples, True)) self.plot_frequency_curve_3D_menu = self.menu.addMenu( qta.icon("mdi.video-3d"), self.tr("Plot Frequency Curve 3D Chart")) self.frequency_3D_plot_selected_action = self.plot_frequency_curve_3D_menu.addAction( self.tr("Plot Selected Samples")) self.frequency_3D_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_3D_chart, self. selections, False)) self.frequency_3D_append_selected_action = self.plot_frequency_curve_3D_menu.addAction( self.tr("Append Selected Samples")) self.frequency_3D_append_selected_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_3D_chart, self. selections, True)) self.frequency_3D_plot_all_action = self.plot_frequency_curve_3D_menu.addAction( self.tr("Plot All Samples")) self.frequency_3D_plot_all_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_3D_chart, self. __dataset.samples, False)) self.frequency_3D_append_all_action = self.plot_frequency_curve_3D_menu.addAction( self.tr("Append All Samples")) self.frequency_3D_append_all_action.triggered.connect( lambda: self.plot_chart(self.frequency_curve_3D_chart, self. __dataset.samples, True)) self.folk54_GSM_diagram_menu = self.menu.addMenu( qta.icon("mdi.triangle-outline"), self.tr("Plot GSM Diagram (Folk, 1954)")) self.folk54_GSM_plot_selected_action = self.folk54_GSM_diagram_menu.addAction( self.tr("Plot Selected Samples")) self.folk54_GSM_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.folk54_GSM_diagram_chart, self. selections, False)) self.folk54_GSM_append_selected_action = self.folk54_GSM_diagram_menu.addAction( self.tr("Append Selected Samples")) self.folk54_GSM_append_selected_action.triggered.connect( lambda: self.plot_chart(self.folk54_GSM_diagram_chart, self. selections, True)) self.folk54_GSM_plot_all_action = self.folk54_GSM_diagram_menu.addAction( self.tr("Plot All Samples")) self.folk54_GSM_plot_all_action.triggered.connect( lambda: self.plot_chart(self.folk54_GSM_diagram_chart, self. __dataset.samples, False)) self.folk54_GSM_append_all_action = self.folk54_GSM_diagram_menu.addAction( self.tr("Append All Samples")) self.folk54_GSM_append_all_action.triggered.connect( lambda: self.plot_chart(self.folk54_GSM_diagram_chart, self. __dataset.samples, True)) self.folk54_SSC_diagram_menu = self.menu.addMenu( qta.icon("mdi.triangle-outline"), self.tr("Plot SSC Diagram (Folk, 1954)")) self.folk54_SSC_plot_selected_action = self.folk54_SSC_diagram_menu.addAction( self.tr("Plot Selected Samples")) self.folk54_SSC_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.folk54_SSC_diagram_chart, self. selections, False)) self.folk54_SSC_append_selected_action = self.folk54_SSC_diagram_menu.addAction( self.tr("Append Selected Samples")) self.folk54_SSC_append_selected_action.triggered.connect( lambda: self.plot_chart(self.folk54_SSC_diagram_chart, self. selections, True)) self.folk54_SSC_plot_all_action = self.folk54_SSC_diagram_menu.addAction( self.tr("Plot All Samples")) self.folk54_SSC_plot_all_action.triggered.connect( lambda: self.plot_chart(self.folk54_SSC_diagram_chart, self. __dataset.samples, False)) self.folk54_SSC_append_all_action = self.folk54_SSC_diagram_menu.addAction( self.tr("Append All Samples")) self.folk54_SSC_append_all_action.triggered.connect( lambda: self.plot_chart(self.folk54_SSC_diagram_chart, self. __dataset.samples, True)) self.BP12_GSM_diagram_menu = self.menu.addMenu( qta.icon("mdi.triangle-outline"), self.tr("Plot GSM Diagram (Blott && Pye, 2012)")) self.BP12_GSM_plot_selected_action = self.BP12_GSM_diagram_menu.addAction( self.tr("Plot Selected Samples")) self.BP12_GSM_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.BP12_GSM_diagram_chart, self. selections, False)) self.BP12_GSM_append_selected_action = self.BP12_GSM_diagram_menu.addAction( self.tr("Append Selected Samples")) self.BP12_GSM_append_selected_action.triggered.connect( lambda: self.plot_chart(self.BP12_GSM_diagram_chart, self. selections, True)) self.BP12_GSM_plot_all_action = self.BP12_GSM_diagram_menu.addAction( self.tr("Plot All Samples")) self.BP12_GSM_plot_all_action.triggered.connect( lambda: self.plot_chart(self.BP12_GSM_diagram_chart, self.__dataset .samples, False)) self.BP12_GSM_append_all_action = self.BP12_GSM_diagram_menu.addAction( self.tr("Append All Samples")) self.BP12_GSM_append_all_action.triggered.connect( lambda: self.plot_chart(self.BP12_GSM_diagram_chart, self.__dataset .samples, True)) self.BP12_SSC_diagram_menu = self.menu.addMenu( qta.icon("mdi.triangle-outline"), self.tr("Plot SSC Diagram (Blott && Pye, 2012)")) self.BP12_SSC_plot_selected_action = self.BP12_SSC_diagram_menu.addAction( self.tr("Plot Selected Samples")) self.BP12_SSC_plot_selected_action.triggered.connect( lambda: self.plot_chart(self.BP12_SSC_diagram_chart, self. selections, False)) self.BP12_SSC_append_selected_action = self.BP12_SSC_diagram_menu.addAction( self.tr("Append Selected Samples")) self.BP12_SSC_append_selected_action.triggered.connect( lambda: self.plot_chart(self.BP12_SSC_diagram_chart, self. selections, True)) self.BP12_SSC_plot_all_action = self.BP12_SSC_diagram_menu.addAction( self.tr("Plot All Samples")) self.BP12_SSC_plot_all_action.triggered.connect( lambda: self.plot_chart(self.BP12_SSC_diagram_chart, self.__dataset .samples, False)) self.BP12_SSC_append_all_action = self.BP12_SSC_diagram_menu.addAction( self.tr("Append All Samples")) self.BP12_SSC_append_all_action.triggered.connect( lambda: self.plot_chart(self.BP12_SSC_diagram_chart, self.__dataset .samples, True)) self.save_action = self.menu.addAction(qta.icon("mdi.microsoft-excel"), self.tr("Save Summary")) self.save_action.triggered.connect(self.on_save_clicked) self.data_table.customContextMenuRequested.connect(self.show_menu)
def createEditor(self, parent, option, index): self.combobox = QComboBox(parent) for sft in [4, 5, 6]: self.combobox.addItem(mode_labels[1 << sft], 1 << sft) return self.combobox
def nb_robots_choice_menu(self): self.nb_robots_choice = QComboBox() self.nb_robots_choice.insertItems( 0, ("1 robot", "2 robots", "3 robots", "4 robots")) self.nb_robots_choice.setGeometry(0, 0, 40, 40) self.nb_robots_choice.activated.connect(self.choix_nb_robots)
def __init__(self): QMainWindow.__init__(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle("MIE") self.main_widget = QWidget(self) self.setStyleSheet('QMainWindow {background-color: #8b8b8b}') #cfcfcf self.setWindowIcon(QtGui.QIcon('mie_icon.ico')) #DIAMETER self.label_d = QLabel("Radius [nm|:", self) self.slider_d = QSlider(Qt.Horizontal) self.slider_d.setMinimum(5) self.slider_d.setMaximum(200) self.slider_d.setTickInterval(5) self.slider_d.setValue(50) self.edit_d = QLineEdit(self) self.edit_d.setMaxLength(5) a = self.slider_d.value() self.edit_d.setText(str(a)) self.push_d_down = QPushButton("<", self) self.push_d_up = QPushButton(">", self) #REFRACTIVE INDEX self.label_n = QLabel("Refractiv index (medium):", self) self.slider_n = QSlider(Qt.Horizontal) self.slider_n.setMinimum(100) self.slider_n.setMaximum(300) self.slider_n.setTickInterval(10) self.slider_n.setValue(100) self.edit_n = QLineEdit(self) self.edit_n.setMaxLength(5) n_m = self.slider_n.value() / 100 self.edit_n.setText(str(n_m)) self.push_n_down = QPushButton("<", self) self.push_n_up = QPushButton(">", self) #CROSS SECTION self.label_radio = QLabel("Cross section:", self) self.radiobutton_sca = QRadioButton("Scattering") self.radiobutton_sca.setChecked(True) self.radiobutton_abs = QRadioButton("Absorption") self.radiobutton_ext = QRadioButton("Extinction") csection = "Scattering" #MATERIAL self.label_m = QLabel("Material (Nanosphere):", self) self.cb_m = QComboBox() list_m = ["Gold", "Silver", "Copper"] self.cb_m.addItems(list_m) material = "Gold" #PLOT self.plot_mie = QPushButton("PLOT", self) self.plot_mie.setStyleSheet('QPushButton {background-color: #12E316}') #CLEAR PLOT self.clear_mie = QPushButton("CLEAR", self) self.clear_mie.setStyleSheet('QPushButton {background-color: #FF0505}') #SAVE FILE self.save_mie = QPushButton("SAVE FILE", self) self.save_mie.setStyleSheet('QPushButton {background-color: #cfcfcf}') #LAYOUT CROSS SECTION self.layout_radio = QHBoxLayout() self.layout_radio.addWidget(self.radiobutton_sca) self.layout_radio.addWidget(self.radiobutton_abs) self.layout_radio.addWidget(self.radiobutton_ext) #LAYOUT DIAMETER self.layout_d1 = QHBoxLayout() self.layout_d1.addWidget(self.push_d_down) self.layout_d1.addWidget(self.slider_d) self.layout_d1.addWidget(self.push_d_up) self.layout_d = QVBoxLayout() self.layout_d.addWidget(self.label_d) self.layout_d.addSpacing(1) self.layout_d.addLayout(self.layout_d1) self.layout_d.addSpacing(1) self.layout_d.addWidget(self.edit_d) #LAYOUT REFRACTIVE INDEX self.layout_n1 = QHBoxLayout() self.layout_n1.addWidget(self.push_n_down) self.layout_n1.addWidget(self.slider_n) self.layout_n1.addWidget(self.push_n_up) self.layout_n = QVBoxLayout() self.layout_n.addWidget(self.label_n) self.layout_n.addSpacing(1) self.layout_n.addLayout(self.layout_n1) self.layout_n.addSpacing(1) self.layout_n.addWidget(self.edit_n) #LAYOUT MATERIAL self.layout_m = QVBoxLayout() self.layout_m.addWidget(self.label_m) self.layout_m.addSpacing(1) self.layout_m.addWidget(self.cb_m) #LAYOUT PARAMETER BELOW self.layout_parameter = QHBoxLayout() self.layout_parameter.addLayout(self.layout_n) self.layout_parameter.addLayout(self.layout_d) #LAYOUT PARAMETER RADIO self.layout_parameter_radio = QVBoxLayout() self.layout_parameter_radio.addWidget(self.label_radio) self.layout_parameter_radio.addSpacing(1) self.layout_parameter_radio.addLayout(self.layout_radio) #LAYOUT PARAMETER ABOVE self.layout_parameter_o = QHBoxLayout() self.layout_parameter_o.addLayout(self.layout_m) self.layout_parameter_o.addLayout(self.layout_parameter_radio) #LAYOUT PLOT self.layout_save = QHBoxLayout() self.layout_save.addWidget(self.plot_mie) self.layout_save.addWidget(self.clear_mie) self.layout_save.addWidget(self.save_mie) #CANVAS self.layout_canvas = MplCanvas(self.main_widget, width=8, height=6, a=a, n_m=n_m, material=material, csection=csection) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) self.navi_toolbar = NavigationToolbar(self.layout_canvas, self) #LAYOUT CANVAS PARAMETER self.layout_cp = QVBoxLayout() self.layout_cp.addLayout(self.layout_save) self.layout_cp.addWidget(self.layout_canvas) self.layout_cp.addWidget(self.navi_toolbar) #SETTINGS LABEL self.settings = QLabel( "----------------------------------------------------------------------------------SETTINGS----------------------------------------------------------------------------------", self) self.settings.setAlignment(Qt.AlignCenter) #OVERALL LAYOUT self.layout_all = QVBoxLayout(self.main_widget) self.layout_all.addLayout(self.layout_cp) self.layout_all.addWidget(self.settings) self.layout_all.addLayout(self.layout_parameter_o) self.layout_all.addLayout(self.layout_parameter) #CONNECT self.push_d_down.clicked.connect(self.connect_d_down) self.push_d_up.clicked.connect(self.connect_d_up) self.slider_d.valueChanged.connect(self.connect_d) self.push_n_down.clicked.connect(self.connect_n_down) self.push_n_up.clicked.connect(self.connect_n_up) self.slider_n.valueChanged.connect(self.connect_n) self.plot_mie.clicked.connect(self.connect_plot) self.save_mie.clicked.connect(self.connect_save) self.cb_m.activated.connect(self.connect_cb) self.clear_mie.clicked.connect(self.clear_gui)
def init_ui(self): self.main_layout = QGridLayout(self) # distance self.distance_label = QLabel(self.tr("Distance (Loss) Function")) self.distance_label.setToolTip( self. tr("It's the function to calculate the difference (on the contrary, similarity) between two samples." )) self.distance_combo_box = QComboBox() self.distance_combo_box.addItems(built_in_distances) self.distance_combo_box.setCurrentText("log10MSE") self.distance_combo_box.currentTextChanged.connect( self.on_distance_changed) self.main_layout.addWidget(self.distance_label, 0, 0) self.main_layout.addWidget(self.distance_combo_box, 0, 1) # minimizer self.minimizer_label = QLabel(self.tr("Minimizer")) self.minimizer_label.setToolTip( self. tr("The algorithm to find the minimum value of the distance function." )) self.minimizer_combo_box = QComboBox() self.minimizer_combo_box.addItems(built_in_minimizers) self.minimizer_combo_box.setCurrentText("SLSQP") self.main_layout.addWidget(self.minimizer_label, 1, 0) self.main_layout.addWidget(self.minimizer_combo_box, 1, 1) # try_GO self.try_GO_checkbox = QCheckBox( self.tr("Try Global Optimization (GO)")) self.try_GO_checkbox.setChecked(False) self.try_GO_checkbox.setToolTip( self.tr("Whether to try global optimization.")) self.main_layout.addWidget(self.try_GO_checkbox, 2, 0, 1, 2) # GO_max_niter self.GO_max_niter_label = QLabel( self.tr("[GO] Maximum N<sub>iteration</sub>")) self.GO_max_niter_label.setToolTip( self. tr("Maximum number of iterations of global optimization for termination." )) self.GO_max_niter_input = QSpinBox() self.GO_max_niter_input.setRange(0, 10000) self.GO_max_niter_input.setValue(100) self.main_layout.addWidget(self.GO_max_niter_label, 3, 0) self.main_layout.addWidget(self.GO_max_niter_input, 3, 1) # GO_success_niter self.GO_success_niter_label = QLabel( self.tr("[GO] Success N<sub>iteration</sub>")) self.GO_success_niter_label.setToolTip( self. tr("The number of iteration that reaching the same local optimal value for termination." )) self.GO_success_niter_input = QSpinBox() self.GO_success_niter_input.setRange(1, 100) self.GO_success_niter_input.setValue(5) self.main_layout.addWidget(self.GO_success_niter_label, 4, 0) self.main_layout.addWidget(self.GO_success_niter_input, 4, 1) # GO_step self.GO_step_label = QLabel(self.tr("[GO] Step Size")) self.GO_step_label.setToolTip( self.tr("The step size of searching global optimal value.")) self.GO_step_input = QDoubleSpinBox() self.GO_step_input.setRange(0.01, 10) self.GO_step_input.setValue(0.1) self.main_layout.addWidget(self.GO_step_label, 5, 0) self.main_layout.addWidget(self.GO_step_input, 5, 1) # GO_minimizer_tol self.GO_minimizer_tol_label = QLabel( self.tr("[GO] Minimizer -lg(loss<sub>tolerance</sub>)")) self.GO_minimizer_tol_label.setToolTip( self. tr("Controls the tolerance of the loss function for termination.")) self.GO_minimizer_tol_input = QSpinBox() self.GO_minimizer_tol_input.setRange(1, 100) self.GO_minimizer_tol_input.setValue(6) self.main_layout.addWidget(self.GO_minimizer_tol_label, 6, 0) self.main_layout.addWidget(self.GO_minimizer_tol_input, 6, 1) # GO_minimizer_ftol self.GO_minimizer_ftol_label = QLabel( self.tr("[GO] Minimizer -lg(δ<sub>loss</sub>)")) self.GO_minimizer_ftol_label.setToolTip( self. tr("Controls the precision goal for the value of loss function in the stopping criterion." )) self.GO_minimizer_ftol_input = QSpinBox() self.GO_minimizer_ftol_input.setRange(1, 100) self.GO_minimizer_ftol_input.setValue(8) self.main_layout.addWidget(self.GO_minimizer_ftol_label, 7, 0) self.main_layout.addWidget(self.GO_minimizer_ftol_input, 7, 1) # GO_minimizer_max_niter self.GO_minimizer_max_niter_label = QLabel( self.tr("[GO] Minimizer Maximum N<sub>iteration</sub>")) self.GO_minimizer_max_niter_label.setToolTip( self. tr("Maximum number of iterations of the minimizer of global optimization." )) self.GO_minimizer_max_niter_input = QSpinBox() self.GO_minimizer_max_niter_input.setRange(0, 100000) self.GO_minimizer_max_niter_input.setValue(500) self.main_layout.addWidget(self.GO_minimizer_max_niter_label, 8, 0) self.main_layout.addWidget(self.GO_minimizer_max_niter_input, 8, 1) # FLO_tol self.FLO_tol_label = QLabel( self.tr("[FLO] -lg(loss<sub>tolerance</sub>)")) self.FLO_tol_label.setToolTip( self. tr("Controls the tolerance of the loss function for termination.")) self.FLO_tol_input = QSpinBox() self.FLO_tol_input.setRange(1, 100) self.FLO_tol_input.setValue(8) self.main_layout.addWidget(self.FLO_tol_label, 9, 0) self.main_layout.addWidget(self.FLO_tol_input, 9, 1) # FLO_ftol self.FLO_ftol_label = QLabel(self.tr("[FLO] -lg(δ<sub>loss</sub>)")) self.FLO_ftol_label.setToolTip( self. tr("Controls the precision goal for the value of loss function in the stopping criterion." )) self.FLO_ftol_input = QSpinBox() self.FLO_ftol_input.setRange(1, 100) self.FLO_ftol_input.setValue(10) self.main_layout.addWidget(self.FLO_ftol_label, 10, 0) self.main_layout.addWidget(self.FLO_ftol_input, 10, 1) # FLO_max_niter self.FLO_max_niter_label = QLabel( self.tr("[FLO] Maximum N<sub>iteration</sub>")) self.FLO_max_niter_label.setToolTip( self. tr("Maximum number of iterations of the minimizer of final local optimization." )) self.FLO_max_niter_input = QSpinBox() self.FLO_max_niter_input.setRange(100, 100000) self.FLO_max_niter_input.setValue(1000) self.main_layout.addWidget(self.FLO_max_niter_label, 11, 0) self.main_layout.addWidget(self.FLO_max_niter_input, 11, 1)
def __init__(self, parent=None): super().__init__(parent) layout = QFormLayout() self.setLayout(layout) self._model = None # Block properties --------------------------------------------------------------------------------------------- self.duration = QWidget() self.duration.setContentsMargins(0, 0, 0, 0) ly = QHBoxLayout() ly.setContentsMargins(0, 0, 0, 0) self.duration.setLayout(ly) self.duration_base = QDoubleSpinBox() self.duration_base.setRange(0, 1000) self.duration_base.setValue(10) self.duration_deviation = QDoubleSpinBox() self.duration_deviation.setRange(0, 10) self.duration_deviation.setValue(0) self.duration_deviation.setSingleStep(0.1) self.duration_deviation.setSuffix(" s") self.duration_base.valueChanged.connect(self.duration_deviation.setMaximum) ly.addWidget(self.duration_base) ly.addWidget(QLabel("±")) ly.addWidget(self.duration_deviation) self.feedback_source = QLineEdit("All") self.feedback_type = QComboBox() self.feedback_type.addItem("Baseline") self.feedback_type.addItem("Feedback") self.mock_signal_path = QLineEdit() self.mock_signal_dataset = QLineEdit() self.mock_previous = QSpinBox() self.mock_previous_reverse = QCheckBox() self.mock_previous_random = QCheckBox() self.pause = QCheckBox() self.beep = QCheckBox() self.start_data_driven_filter_designer = QCheckBox() self.update_statistics = QCheckBox() self.update_statistics.stateChanged.connect(lambda state: self.statistics_type.setEnabled(bool(state))) self.statistics_type = QComboBox() self.statistics_type.setEnabled(False) for name in self.statistics_name_to_type: self.statistics_type.addItem(name) self.statistics_type.setCurrentText("Standardise") self.random_bound = QComboBox() self.random_bound.addItem("SimCircle") self.random_bound.addItem("RandomCircle") self.random_bound.addItem("Bar") self.video_path = QLineEdit() self.message = QLineEdit() self.feedback_type.currentTextChanged.connect(lambda ftype: self.message.setEnabled(ftype == "Baseline")) self.voiceover = QCheckBox() # Grouped properties ------------------------------------------------------------------------------------------- # Mock signal mock_signal_groupbox = QGroupBox("Mock signal") mock_signal_gblayout = QFormLayout() mock_signal_groupbox.setLayout(mock_signal_gblayout) mock_signal_gblayout.addRow("Mock signal file path", self.mock_signal_path) mock_signal_gblayout.addRow("Mock signal file dataset", self.mock_signal_dataset) mock_signal_gblayout.addRow("Mock previous", self.mock_previous) mock_signal_gblayout.addRow("Reverse mock previous", self.mock_previous_reverse) mock_signal_gblayout.addRow("Random mock previous", self.mock_previous_random) # After block actions after_block_groupbox = QGroupBox("After block actions") after_block_gblayout = QFormLayout() after_block_groupbox.setLayout(after_block_gblayout) after_block_gblayout.addRow("Start data driven filter designer", self.start_data_driven_filter_designer) after_block_gblayout.addRow("Pause", self.pause) after_block_gblayout.addRow("Beep", self.beep) after_block_gblayout.addRow("Update statistics", self.update_statistics) after_block_gblayout.addRow("Statistics type", self.statistics_type) # Adding properties to the widget ------------------------------------------------------------------------------ layout.addRow("Duration", self.duration) layout.addRow("Source", self.feedback_source) layout.addRow("FB Type", self.feedback_type) layout.addRow("Random bound", self.random_bound) layout.addRow("Video path", self.video_path) layout.addRow("Message for test subject", self.message) layout.addRow("Voiceover for message", self.voiceover) layout.addRow(mock_signal_groupbox) layout.addRow(after_block_groupbox)
def _widget(self): widget = QComboBox() widget.addItems(self.__options) widget.setEditable(False) return widget
def __init__(self,*args,**kwargs): super(ExportFileDialog,self).__init__(*args,**kwargs) self.mainWindow = self.parent() self.setWindowTitle("Export nodes to CSV") self.setAcceptMode(QFileDialog.AcceptSave) self.setOption(QFileDialog.DontUseNativeDialog) #self.setFilter("CSV Files (*.csv)") self.setDefaultSuffix("csv") self.optionBOM = QCheckBox("Use a BOM",self) self.optionBOM.setCheckState(Qt.CheckState.Checked) self.optionLinebreaks = QCheckBox("Remove line breaks",self) self.optionLinebreaks.setCheckState(Qt.CheckState.Checked) self.optionSeparator = QComboBox(self) self.optionSeparator.insertItems(0, [";","\\t",","]) self.optionSeparator.setEditable(True) # if none or all are selected, export all # if one or more are selected, export selective self.optionAll = QComboBox(self) self.optionAll.insertItems(0, ['All nodes (faster for large datasets, ordered by internal ID)','Selected nodes (ordered like shown in nodes view)']) if self.mainWindow.tree.noneOrAllSelected(): self.optionAll.setCurrentIndex(0) else: self.optionAll.setCurrentIndex(1) layout = self.layout() row = layout.rowCount() layout.addWidget(QLabel('Options'),row,0) options = QHBoxLayout() options.addWidget(self.optionBOM) options.addWidget(self.optionLinebreaks) options.addWidget(QLabel('Separator')) options.addWidget(self.optionSeparator) options.addStretch(1) layout.addLayout(options,row,1,1,2) layout.addWidget(QLabel('Export mode'),row+2,0) layout.addWidget(self.optionAll,row+2,1,1,2) self.setLayout(layout) datadir = self.mainWindow.database.filename if not os.path.exists(datadir): datadir = self.mainWindow.settings.value("lastpath", os.path.expanduser("~")) if not os.path.exists(datadir): datadir = os.path.expanduser("~") datadir = os.path.dirname(datadir) self.setDirectory(datadir) if self.exec_(): try: if os.path.isfile(self.selectedFiles()[0]): os.remove(self.selectedFiles()[0]) except Exception as e: QMessageBox.information(self,"Facepager","Could not overwrite file:"+str(e)) return False output = open(self.selectedFiles()[0], 'w', newline='', encoding='utf8') try: if self.optionBOM.isChecked(): output.write('\ufeff') if self.optionAll.currentIndex() == 0: self.exportAllNodes(output) else: self.exportSelectedNodes(output) finally: output.close()
def __init__(self, image, parent=None): super(PlotsWidget, self).__init__(parent) choices = ['Red', 'Green', 'Blue', 'Hue', 'Saturation', 'Value'] self.xaxis_combo = QComboBox() self.xaxis_combo.addItems(choices) self.xaxis_combo.setCurrentIndex(3) self.yaxis_combo = QComboBox() self.yaxis_combo.addItems(choices) self.yaxis_combo.setCurrentIndex(4) self.sampling_spin = QSpinBox() levels = int(np.log2(min(image.shape[:-1]))) self.sampling_spin.setRange(0, levels) self.sampling_spin.setSpecialValueText(self.tr('Off')) self.sampling_spin.setValue(1) self.sampling_spin.setSuffix(self.tr(' level(s)')) self.size_spin = QSpinBox() self.size_spin.setRange(1, 10) self.size_spin.setValue(2) self.size_spin.setSuffix(self.tr(' pt')) self.style_combo = QComboBox() self.markers = [ ',', '.', 'o', '8', 's', 'p', 'P', '*', 'h', 'H', 'X', 'D' ] self.style_combo.addItems([ 'pixel', 'point', 'circle', 'octa', 'square', 'penta', 'plus', 'star', 'hexa1', 'hexa2', 'cross', 'diamond' ]) self.alpha_spin = QDoubleSpinBox() self.alpha_spin.setRange(0, 1) self.alpha_spin.setDecimals(2) self.alpha_spin.setSingleStep(0.05) self.alpha_spin.setValue(1) self.colors_check = QCheckBox(self.tr('Show colors')) self.grid_check = QCheckBox(self.tr('Show grid')) self.norm_check = QCheckBox(self.tr('Normalized')) self.total_label = QLabel() img = np.copy(image) self.colors = [None] * (levels + 1) for scale in range(levels + 1): rgb = cv.cvtColor(img.astype(np.float32) / 255, cv.COLOR_BGR2RGB) hsv = cv.cvtColor(rgb, cv.COLOR_RGB2HSV) hsv[:, :, 0] /= 360 shape = (img.shape[0] * img.shape[1], img.shape[2]) self.colors[scale] = np.concatenate( (np.reshape(rgb, shape), np.reshape(hsv, shape)), axis=1) img = cv.pyrDown(img) figure = Figure() plot_canvas = FigureCanvas(figure) self.axes = plot_canvas.figure.subplots() self.redraw() figure.set_tight_layout(True) self.xaxis_combo.currentIndexChanged.connect(self.redraw) self.yaxis_combo.currentIndexChanged.connect(self.redraw) self.sampling_spin.valueChanged.connect(self.redraw) self.size_spin.valueChanged.connect(self.redraw) self.style_combo.currentIndexChanged.connect(self.redraw) self.alpha_spin.valueChanged.connect(self.redraw) self.colors_check.stateChanged.connect(self.redraw) self.grid_check.stateChanged.connect(self.redraw) self.norm_check.stateChanged.connect(self.redraw) bottom_layout = QGridLayout() bottom_layout.addWidget(NavigationToolbar(plot_canvas, self), 0, 0, 1, 5) bottom_layout.addWidget(QLabel(self.tr('X axis:')), 1, 0) bottom_layout.addWidget(self.xaxis_combo, 1, 1) bottom_layout.addWidget(QLabel(self.tr('Y Axis:')), 2, 0) bottom_layout.addWidget(self.yaxis_combo, 2, 1) bottom_layout.addWidget(QLabel(self.tr('Subsampling:')), 3, 0) bottom_layout.addWidget(self.sampling_spin, 3, 1) bottom_layout.addWidget(QLabel(self.tr('Point size:')), 1, 2) bottom_layout.addWidget(self.size_spin, 1, 3) bottom_layout.addWidget(QLabel(self.tr('Point style:')), 2, 2) bottom_layout.addWidget(self.style_combo, 2, 3) bottom_layout.addWidget(QLabel(self.tr('Point alpha:')), 3, 2) bottom_layout.addWidget(self.alpha_spin, 3, 3) bottom_layout.addWidget(self.colors_check, 1, 4) bottom_layout.addWidget(self.grid_check, 2, 4) bottom_layout.addWidget(self.total_label, 3, 4) main_layout = QVBoxLayout() main_layout.addWidget(plot_canvas) main_layout.addLayout(bottom_layout) self.setLayout(main_layout)
def _init_load_options_tab(self, tab): if self.is_blob: blob_layout = QGridLayout() # architecture selection arch_caption = QLabel(self) arch_caption.setText('Architecture:') blob_layout.addWidget(arch_caption, 0, 0) arch = QComboBox(self) for a in archinfo.all_arches: arch.addItem(f'{a.bits}b {a.name} ({a.memory_endness[-2:]})') blob_layout.addWidget(arch, 0, 1) self.option_widgets['arch'] = arch # load address base_addr_caption = QLabel(self) base_addr_caption.setText('Base Address:') blob_layout.addWidget(base_addr_caption, 1, 0) base_addr = QLineEdit(self) base_addr.setText('0') blob_layout.addWidget(base_addr, 1, 1) self.option_widgets['base_addr'] = base_addr # entry address entry_addr_caption = QLabel(self) entry_addr_caption.setText('Entry Address:') blob_layout.addWidget(entry_addr_caption, 2, 0) entry_addr = QLineEdit(self) entry_addr.setText('0') blob_layout.addWidget(entry_addr, 2, 1) self.option_widgets['entry_addr'] = entry_addr # load debug symbols load_debug_info = QCheckBox() load_debug_info.setText("Load debug information if available") load_debug_info.setChecked(True) self.option_widgets['load_debug_info'] = load_debug_info # auto load libs auto_load_libs = QCheckBox() auto_load_libs.setText( "Automatically load all libraries (slow, not recommended)") auto_load_libs.setChecked(False) self.option_widgets['auto_load_libs'] = auto_load_libs # dependencies list dep_group = QGroupBox("Dependencies") dep_list = QListWidget() self.option_widgets['dep_list'] = dep_list sublayout = QVBoxLayout() sublayout.addWidget(dep_list) dep_group.setLayout(sublayout) layout = QVBoxLayout() if self.is_blob: layout.addLayout(blob_layout) layout.addWidget(load_debug_info) layout.addWidget(auto_load_libs) layout.addWidget(dep_group) layout.addStretch(0) frame = QFrame(self) frame.setLayout(layout) tab.addTab(frame, "Loading Options")
def __init__(self, image, parent=None): super(CloningWidget, self).__init__(parent) self.detector_combo = QComboBox() self.detector_combo.addItems( [self.tr("BRISK"), self.tr("ORB"), self.tr("AKAZE")]) self.detector_combo.setCurrentIndex(0) self.detector_combo.setToolTip( self.tr("Algorithm used for localization and description")) self.response_spin = QSpinBox() self.response_spin.setRange(0, 100) self.response_spin.setSuffix(self.tr("%")) self.response_spin.setValue(90) self.response_spin.setToolTip( self.tr("Maximum keypoint response to perform matching")) self.matching_spin = QSpinBox() self.matching_spin.setRange(1, 100) self.matching_spin.setSuffix(self.tr("%")) self.matching_spin.setValue(20) self.matching_spin.setToolTip( self.tr("Maximum metric difference to accept matching")) self.distance_spin = QSpinBox() self.distance_spin.setRange(1, 100) self.distance_spin.setSuffix(self.tr("%")) self.distance_spin.setValue(15) self.distance_spin.setToolTip( self.tr("Maximum distance between matches in the same cluster")) self.cluster_spin = QSpinBox() self.cluster_spin.setRange(1, 20) self.cluster_spin.setValue(5) self.cluster_spin.setToolTip( self.tr("Minimum number of keypoints to create a new cluster")) self.kpts_check = QCheckBox(self.tr("Show keypoints")) self.kpts_check.setToolTip(self.tr("Show keypoint coverage")) self.nolines_check = QCheckBox(self.tr("Hide lines")) self.nolines_check.setToolTip(self.tr("Disable match line drawing")) self.process_button = QToolButton() self.process_button.setText(self.tr("Process")) self.process_button.setToolTip(self.tr("Perform automatic detection")) modify_font(self.process_button, bold=True) self.status_label = QLabel() self.mask_label = QLabel() self.mask_button = QToolButton() self.mask_button.setText(self.tr("Load mask...")) self.mask_button.setToolTip( self.tr("Load an image to be used as mask")) self.onoff_button = QToolButton() self.onoff_button.setText(self.tr("OFF")) self.onoff_button.setCheckable(True) self.onoff_button.setToolTip(self.tr("Toggle keypoint detection mask")) self.image = image self.viewer = ImageViewer(self.image, self.image) self.gray = cv.cvtColor(self.image, cv.COLOR_BGR2GRAY) self.total = self.kpts = self.desc = self.matches = self.clusters = self.mask = None self.canceled = False self.detector_combo.currentIndexChanged.connect(self.update_detector) self.response_spin.valueChanged.connect(self.update_detector) self.matching_spin.valueChanged.connect(self.update_matching) self.distance_spin.valueChanged.connect(self.update_cluster) self.cluster_spin.valueChanged.connect(self.update_cluster) self.nolines_check.stateChanged.connect(self.process) self.kpts_check.stateChanged.connect(self.process) self.process_button.clicked.connect(self.process) self.mask_button.clicked.connect(self.load_mask) self.onoff_button.toggled.connect(self.toggle_mask) self.onoff_button.setEnabled(False) top_layout = QHBoxLayout() top_layout.addWidget(QLabel(self.tr("Detector:"))) top_layout.addWidget(self.detector_combo) top_layout.addWidget(QLabel(self.tr("Response:"))) top_layout.addWidget(self.response_spin) top_layout.addWidget(QLabel(self.tr("Matching:"))) top_layout.addWidget(self.matching_spin) top_layout.addWidget(QLabel(self.tr("Distance:"))) top_layout.addWidget(self.distance_spin) top_layout.addWidget(QLabel(self.tr("Cluster:"))) top_layout.addWidget(self.cluster_spin) top_layout.addWidget(self.nolines_check) top_layout.addWidget(self.kpts_check) top_layout.addStretch() bottom_layout = QHBoxLayout() bottom_layout.addWidget(self.process_button) bottom_layout.addWidget(self.status_label) bottom_layout.addStretch() bottom_layout.addWidget(self.mask_button) bottom_layout.addWidget(self.onoff_button) main_layout = QVBoxLayout() main_layout.addLayout(top_layout) main_layout.addLayout(bottom_layout) main_layout.addWidget(self.viewer) self.setLayout(main_layout)
def __init__(self, parent=None): super(NGL_HKLViewer, self).__init__(parent) self.verbose = 0 self.UseOSbrowser = False self.jscriptfname = "" self.devmode = False self.hklfname = "" self.handshakewait = 5 for e in sys.argv: if "verbose" in e: self.verbose = e.split("verbose=")[1] if "UseOSbrowser" in e: self.UseOSbrowser = e.split("UseOSbrowser=")[1] if "jscriptfname" in e: self.jscriptfname = e.split("jscriptfname=")[1] if "devmode" in e: self.devmode = True if 'htmlfname' in e: self.hklfname = e.split("htmlfname=")[1] if 'handshakewait' in e: self.handshakewait = e.split('handshakewait=')[1] self.zmq_context = None self.bufsize = 20000 self.originalPalette = QApplication.palette() self.openFileNameButton = QPushButton("Load reflection file") self.openFileNameButton.setDefault(True) self.openFileNameButton.clicked.connect(self.OpenReflectionsFile) self.debugbutton = QPushButton("Debug") self.debugbutton.clicked.connect(self.DebugInteractively) self.settingsbtn = QPushButton("Settings") self.settingsbtn.clicked.connect(self.SettingsDialog) self.mousemoveslider = QSlider(Qt.Horizontal) self.mousemoveslider.setMinimum(0) self.mousemoveslider.setMaximum(300) self.mousemoveslider.setValue(0) self.mousemoveslider.sliderReleased.connect( self.onFinalMouseSensitivity) self.mousemoveslider.valueChanged.connect(self.onMouseSensitivity) self.mousesensitxtbox = QLineEdit('') self.mousesensitxtbox.setReadOnly(True) self.fontspinBox = QDoubleSpinBox() self.fontspinBox.setSingleStep(1) self.fontspinBox.setRange(4, 50) self.font = QFont() self.font.setFamily(self.font.defaultFamily()) self.fontspinBox.setValue(self.font.pointSize()) #self.fontspinBox.setValue(self.font.pixelSize()) self.fontspinBox.valueChanged.connect(self.onFontsizeChanged) self.Fontsize_labeltxt = QLabel() self.Fontsize_labeltxt.setText("Font size:") self.cameraPerspectCheckBox = QCheckBox() self.cameraPerspectCheckBox.setText("Perspective camera") self.cameraPerspectCheckBox.clicked.connect(self.onCameraPerspect) self.cameraPerspectCheckBox.setCheckState(Qt.Unchecked) self.settingsform = SettingsForm(self) self.MillerComboBox = QComboBox() self.MillerComboBox.activated.connect(self.onMillerComboSelchange) #self.MillerComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.MillerLabel = QLabel() self.MillerLabel.setText("Selected HKL Scene") self.HKLnameedit = QLineEdit('') self.HKLnameedit.setReadOnly(True) self.textInfo = QTextEdit() self.textInfo.setLineWrapMode(QTextEdit.NoWrap) self.textInfo.setReadOnly(True) labels = [ "Label", "Type", "no. of HKLs", "Span of HKLs", "Min Max data", "Min Max sigmas", "d_min, d_max", "Symmetry unique", "Anomalous" ] self.millertable = QTableWidget(0, len(labels)) self.millertable.setHorizontalHeaderLabels(labels) self.millertable.horizontalHeader().setDefaultAlignment(Qt.AlignLeft) # don't allow editing this table self.millertable.setEditTriggers(QTableWidget.NoEditTriggers) self.createExpansionBox() self.createFileInfoBox() self.CreateSliceTabs() self.createRadiiScaleGroupBox() self.createBinsBox() self.CreateFunctionTabs() mainLayout = QGridLayout() mainLayout.addWidget(self.FileInfoBox, 0, 0) mainLayout.addWidget(self.MillerLabel, 1, 0) mainLayout.addWidget(self.MillerComboBox, 2, 0) mainLayout.addWidget(self.functionTabWidget, 3, 0) mainLayout.addWidget(self.settingsbtn, 4, 0, 1, 1) #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) ) if self.UseOSbrowser == False: self.BrowserBox = QWebEngineView() mainLayout.addWidget(self.BrowserBox, 0, 1, 5, 3) self.BrowserBox.setUrl("https://cctbx.github.io/") #self.BrowserBox.setUrl("https://webglreport.com/") #self.BrowserBox.loadFinished.connect(self.onLoadFinished) mainLayout.setColumnStretch(2, 1) mainLayout.setRowStretch(0, 1) mainLayout.setRowStretch(1, 0) mainLayout.setRowStretch(2, 1) mainLayout.setRowStretch(3, 1) mainLayout.setColumnStretch(4, 0) self.setLayout(mainLayout) self.setWindowTitle("HKL-Viewer") self.cctbxproc = None self.LaunchCCTBXPython() self.out = None self.err = None self.comboviewwidth = 0 self.hklscenes_arrays = [] self.array_infotpls = [] self.matching_arrays = [] self.bin_infotpls = None self.bin_opacities = None self.html_url = "" self.spacegroups = [] self.info = [] self.infostr = "" self.fileisvalid = False self.NewFileLoaded = False self.NewHKLscenes = False self.updatingNbins = False self.binstableitemchanges = False self.show()
def createInterface(self): layout = QHBoxLayout() buttonToInvert = None ''' Adding title ''' self.setWindowTitle('Convertisseur de devises') ''' Adding style of window ''' self.setStyleSheet(''.join(['background-color:', '#333', ';'])) ''' Adding width and height ''' self.setMinimumSize(800, 250) ''' Adding UI ''' self.buttonToInvert = QPushButton('Inverser devises') self.currentCurrency['input'] = QLineEdit() self.currentCurrency['select'] = QComboBox() self.targetCurrency['input'] = QLineEdit() self.targetCurrency['select'] = QComboBox() ''' Adding datas ''' self.currentCurrency['select'].addItems(self.currencies) self.targetCurrency['select'].addItems(self.currencies) self.initDefaultCurrency(self.currentCurrency['select'], self.currentCurrency['code']) self.initDefaultCurrency(self.targetCurrency['select'], self.targetCurrency['code']) self.currentCurrency['input'].setText(str(1)) self.changeInput(self.targetCurrency['update'], True) ''' Adding style ''' self.currentCurrency['input'].setFixedWidth(150) self.currentCurrency['select'].setFixedWidth(150) self.targetCurrency['input'].setFixedWidth(150) self.targetCurrency['select'].setFixedWidth(150) self.buttonToInvert.setFixedWidth(150) self.currentCurrency['input'].setStyleSheet(''.join(['color:', '#FFFFFF', ';'])) self.currentCurrency['select'].setStyleSheet(''.join(['color:', '#FFFFFF', ';'])) self.targetCurrency['input'].setStyleSheet(''.join(['color:', '#FFFFFF', ';'])) self.targetCurrency['select'].setStyleSheet(''.join(['color:', '#FFFFFF', ';'])) self.buttonToInvert.setStyleSheet(''.join(['color:', '#FFFFFF', ';'])) ''' Adding events ''' self.currentCurrency['select'].currentIndexChanged.connect(self.onCurrentCurrencyChange) self.targetCurrency['select'].currentIndexChanged.connect(self.onTargetCurrencyChange) self.currentCurrency['input'].textChanged.connect(self.onCurrentAmountChange) self.targetCurrency['input'].textChanged.connect(self.onTargetAmountChange) self.buttonToInvert.clicked.connect(self.onClick) ''' Adding elements to the interface ''' layout.addWidget(self.currentCurrency['select']) layout.addWidget(self.currentCurrency['input']) layout.addWidget(self.targetCurrency['select']) layout.addWidget(self.targetCurrency['input']) layout.addWidget(self.buttonToInvert) self.setLayout(layout)
def CreateSliceTabs(self): self.showslicecheckbox = QCheckBox() self.showslicecheckbox.setText("Show Slice") self.showslicecheckbox.clicked.connect(self.showSlice) self.sliceindexspinBox = QDoubleSpinBox() self.sliceindex = 0 self.sliceindexspinBox.setValue(self.sliceindex) self.sliceindexspinBox.setDecimals(0) self.sliceindexspinBox.setSingleStep(1) self.sliceindexspinBox.setRange(0, 20) self.sliceindexspinBox.valueChanged.connect(self.onSliceIndexChanged) self.SliceLabelComboBox = QComboBox() self.SliceLabelComboBox.activated.connect(self.onSliceComboSelchange) self.sliceaxis = ["h", "k", "l"] self.SliceLabelComboBox.addItems(self.sliceaxis) self.SliceLabelComboBox.setDisabled(True) self.sliceindexspinBox.setDisabled(True) self.sliceTabWidget = QTabWidget() tab1 = QWidget() layout1 = QGridLayout() layout1.addWidget(self.showslicecheckbox, 0, 0, 1, 1) layout1.addWidget(self.SliceLabelComboBox, 0, 1, 1, 1) layout1.addWidget(self.sliceindexspinBox, 0, 2, 1, 1) tab1.setLayout(layout1) tab2 = QWidget() layout2 = QGridLayout() self.hvec_spinBox = QDoubleSpinBox(self.sliceTabWidget) self.hvecval = 2.0 self.hvec_spinBox.setValue(self.hvecval) self.hvec_spinBox.setDecimals(2) self.hvec_spinBox.setSingleStep(0.5) self.hvec_spinBox.setRange(-100.0, 10.0) self.hvec_spinBox.valueChanged.connect(self.onHvecChanged) self.hvec_Label = QLabel() self.hvec_Label.setText("H") layout2.addWidget(self.hvec_Label, 0, 0, 1, 1) layout2.addWidget(self.hvec_spinBox, 0, 1, 1, 1) self.kvec_spinBox = QDoubleSpinBox(self.sliceTabWidget) self.kvecval = 0.0 self.kvec_spinBox.setValue(self.kvecval) self.kvec_spinBox.setDecimals(2) self.kvec_spinBox.setSingleStep(0.5) self.kvec_spinBox.setRange(-100.0, 100.0) self.kvec_spinBox.valueChanged.connect(self.onKvecChanged) self.kvec_Label = QLabel() self.kvec_Label.setText("K") layout2.addWidget(self.kvec_Label, 1, 0, 1, 1) layout2.addWidget(self.kvec_spinBox, 1, 1, 1, 1) self.lvec_spinBox = QDoubleSpinBox(self.sliceTabWidget) self.lvecval = 0.0 self.lvec_spinBox.setValue(self.lvecval) self.lvec_spinBox.setDecimals(2) self.lvec_spinBox.setSingleStep(0.5) self.lvec_spinBox.setRange(-100.0, 100.0) self.lvec_spinBox.valueChanged.connect(self.onLvecChanged) self.lvec_Label = QLabel() self.lvec_Label.setText("L") layout2.addWidget(self.lvec_Label, 2, 0, 1, 1) layout2.addWidget(self.lvec_spinBox, 2, 1, 1, 1) self.hkldist_spinBox = QDoubleSpinBox(self.sliceTabWidget) self.hkldistval = 0.0 self.hkldist_spinBox.setValue(self.hkldistval) self.hkldist_spinBox.setDecimals(2) self.hkldist_spinBox.setSingleStep(0.5) self.hkldist_spinBox.setRange(-100.0, 100.0) self.hkldist_spinBox.valueChanged.connect(self.onHKLdistChanged) self.hkldist_Label = QLabel() self.hkldist_Label.setText("Distance from Origin") layout2.addWidget(self.hkldist_Label, 3, 0, 1, 1) layout2.addWidget(self.hkldist_spinBox, 3, 1, 1, 1) self.clipwidth_spinBox = QDoubleSpinBox(self.sliceTabWidget) self.clipwidthval = 0.5 self.clipwidth_spinBox.setValue(self.clipwidthval) self.clipwidth_spinBox.setDecimals(2) self.clipwidth_spinBox.setSingleStep(0.05) self.clipwidth_spinBox.setRange(0.0, 100.0) self.clipwidth_spinBox.valueChanged.connect(self.onClipwidthChanged) self.clipwidth_Label = QLabel() self.clipwidth_Label.setText("Clip Plane Width") layout2.addWidget(self.clipwidth_Label, 4, 0, 1, 1) layout2.addWidget(self.clipwidth_spinBox, 4, 1, 1, 1) self.ClipBox = QGroupBox("Normal Vector to Clip Plane") self.ClipBox.setLayout(layout2) layout3 = QGridLayout() self.ClipPlaneChkBox = QCheckBox(self.sliceTabWidget) self.ClipPlaneChkBox.setText( "Use clip plane normal to HKL vector pointing out") self.ClipPlaneChkBox.clicked.connect(self.onClipPlaneChkBox) layout3.addWidget(self.ClipPlaneChkBox, 0, 0) layout3.addWidget(self.ClipBox, 1, 0) tab2.setLayout(layout3) self.sliceTabWidget.addTab(tab1, "Explicit Slicing") self.sliceTabWidget.addTab(tab2, "Clip Plane Slicing") self.ClipBox.setDisabled(True)
def initDifficultyLayout(self): self.difficultyPage = QWidget() self.difficultyLayout = QGridLayout() self.difficultyLayout.setAlignment(Qt.AlignTop) self.difficultyPage.setLayout(self.difficultyLayout) self.playerCoalitionSkill = QComboBox() self.enemyCoalitionSkill = QComboBox() self.enemyAASkill = QComboBox() for skill in CONST.SKILL_OPTIONS: self.playerCoalitionSkill.addItem(skill) self.enemyCoalitionSkill.addItem(skill) self.enemyAASkill.addItem(skill) self.playerCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.player_skill)) self.enemyCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill)) self.enemyAASkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill)) self.playerCoalitionSkill.currentIndexChanged.connect(self.applySettings) self.enemyCoalitionSkill.currentIndexChanged.connect(self.applySettings) self.enemyAASkill.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0) self.difficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1, Qt.AlignRight) self.difficultyLayout.addWidget(QLabel("Enemy skill"), 1, 0) self.difficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight) self.difficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"), 2, 0) self.difficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight) self.difficultyLabel = QComboBox() [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS] self.difficultyLabel.setCurrentIndex(CONST.LABELS_OPTIONS.index(self.game.settings.labels)) self.difficultyLabel.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("In Game Labels"), 3, 0) self.difficultyLayout.addWidget(self.difficultyLabel, 3, 1, Qt.AlignRight) self.noNightMission = QCheckBox() self.noNightMission.setChecked(self.game.settings.night_disabled) self.noNightMission.toggled.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("No night missions"), 4, 0) self.difficultyLayout.addWidget(self.noNightMission, 4, 1, Qt.AlignRight) self.mapVisibiitySelection = QComboBox() self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All: self.mapVisibiitySelection.setCurrentIndex(0) self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies: self.mapVisibiitySelection.setCurrentIndex(1) self.mapVisibiitySelection.addItem("Allies Only", ForcedOptions.Views.OnlyAllies) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyAllies: self.mapVisibiitySelection.setCurrentIndex(2) self.mapVisibiitySelection.addItem("Own Aircraft Only", ForcedOptions.Views.MyAircraft) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.MyAircraft: self.mapVisibiitySelection.setCurrentIndex(3) self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap) if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap: self.mapVisibiitySelection.setCurrentIndex(4) self.mapVisibiitySelection.currentIndexChanged.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Map visibility options"), 5, 0) self.difficultyLayout.addWidget(self.mapVisibiitySelection, 5, 1, Qt.AlignRight) self.ext_views = QCheckBox() self.ext_views.setChecked(self.game.settings.external_views_allowed) self.ext_views.toggled.connect(self.applySettings) self.difficultyLayout.addWidget(QLabel("Allow external views"), 6, 0) self.difficultyLayout.addWidget(self.ext_views, 6, 1, Qt.AlignRight)
def __init__(self): QMainWindow.__init__(self) # Title and dimensions self.setWindowTitle("Patterns detection") self.setGeometry(0, 0, 800, 500) # Main menu bar self.menu = self.menuBar() self.menu_file = self.menu.addMenu("File") exit = QAction("Exit", self, triggered=qApp.quit) self.menu_file.addAction(exit) self.menu_about = self.menu.addMenu("&About") about = QAction("About Qt", self, shortcut=QKeySequence(QKeySequence.HelpContents), triggered=qApp.aboutQt) self.menu_about.addAction(about) # Create a label for the display camera self.label = QLabel(self) self.label.setFixedSize(640, 480) # Thread in charge of updating the image self.th = Thread(self) self.th.finished.connect(self.close) self.th.updateFrame.connect(self.setImage) # Model group self.group_model = QGroupBox("Trained model") self.group_model.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) model_layout = QHBoxLayout() self.combobox = QComboBox() for xml_file in os.listdir(cv2.data.haarcascades): if xml_file.endswith(".xml"): self.combobox.addItem(xml_file) model_layout.addWidget(QLabel("File:"), 10) model_layout.addWidget(self.combobox, 90) self.group_model.setLayout(model_layout) # Buttons layout buttons_layout = QHBoxLayout() self.button1 = QPushButton("Start") self.button2 = QPushButton("Stop/Close") self.button1.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.button2.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) buttons_layout.addWidget(self.button2) buttons_layout.addWidget(self.button1) right_layout = QHBoxLayout() right_layout.addWidget(self.group_model, 1) right_layout.addLayout(buttons_layout, 1) # Main layout layout = QVBoxLayout() layout.addWidget(self.label) layout.addLayout(right_layout) # Central widget widget = QWidget(self) widget.setLayout(layout) self.setCentralWidget(widget) # Connections self.button1.clicked.connect(self.start) self.button2.clicked.connect(self.kill_thread) self.button2.setEnabled(False) self.combobox.currentTextChanged.connect(self.set_model)
def __init__(self, game: Game, package: Package, parent=None) -> None: super().__init__(parent=parent) self.game = game self.package = package self.custom_name_text = None self.country = self.game.player_country self.setWindowTitle("Create flight") self.setWindowIcon(EVENT_ICONS["strike"]) layout = QVBoxLayout() self.task_selector = QFlightTypeComboBox(self.game.theater, package.target) self.task_selector.setCurrentIndex(0) self.task_selector.currentTextChanged.connect(self.on_task_changed) layout.addLayout(QLabeledWidget("Task:", self.task_selector)) self.aircraft_selector = QAircraftTypeSelector( self.game.aircraft_inventory.available_types_for_player, self.game.player_country, self.task_selector.currentData()) self.aircraft_selector.setCurrentIndex(0) self.aircraft_selector.currentIndexChanged.connect( self.on_aircraft_changed) layout.addLayout(QLabeledWidget("Aircraft:", self.aircraft_selector)) self.departure = QOriginAirfieldSelector( self.game.aircraft_inventory, [cp for cp in game.theater.controlpoints if cp.captured], self.aircraft_selector.currentData()) self.departure.availability_changed.connect(self.update_max_size) self.departure.currentIndexChanged.connect(self.on_departure_changed) layout.addLayout(QLabeledWidget("Departure:", self.departure)) self.arrival = QArrivalAirfieldSelector( [cp for cp in game.theater.controlpoints if cp.captured], self.aircraft_selector.currentData(), "Same as departure") layout.addLayout(QLabeledWidget("Arrival:", self.arrival)) self.divert = QArrivalAirfieldSelector( [cp for cp in game.theater.controlpoints if cp.captured], self.aircraft_selector.currentData(), "None") layout.addLayout(QLabeledWidget("Divert:", self.divert)) self.flight_size_spinner = QFlightSizeSpinner() self.update_max_size(self.departure.available) layout.addLayout(QLabeledWidget("Size:", self.flight_size_spinner)) self.client_slots_spinner = QFlightSizeSpinner( min_size=0, max_size=self.flight_size_spinner.value(), default_size=0) self.flight_size_spinner.valueChanged.connect( lambda v: self.client_slots_spinner.setMaximum(v)) layout.addLayout( QLabeledWidget("Client Slots:", self.client_slots_spinner)) # When an off-map spawn overrides the start type to in-flight, we save # the selected type into this value. If a non-off-map spawn is selected # we restore the previous choice. self.restore_start_type: Optional[str] = None self.start_type = QComboBox() self.start_type.addItems(["Cold", "Warm", "Runway", "In Flight"]) self.start_type.setCurrentText(self.game.settings.default_start_type) layout.addLayout( QLabeledWidget("Start type:", self.start_type, tooltip="Selects the start type for this flight.")) layout.addWidget( QLabel( "Any option other than Cold will make this flight " + "non-targetable<br />by OCA/Aircraft missions. This will affect " + "game balance.")) self.custom_name = QLineEdit() self.custom_name.textChanged.connect(self.set_custom_name_text) layout.addLayout( QLabeledWidget("Custom Flight Name (Optional)", self.custom_name)) layout.addStretch() self.create_button = QPushButton("Create") self.create_button.clicked.connect(self.create_flight) layout.addWidget(self.create_button, alignment=Qt.AlignRight) self.setLayout(layout) self.on_departure_changed(self.departure.currentIndex())
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex): cb = QComboBox(parent) for spent_category in self.__spent_category_list: cb.addItem(spent_category.name) return cb
def createPropertyTab(self, property_kind): propertyTab = QWidget() propertyTab.property_kind = property_kind propertyTab.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) propertyLayout = QVBoxLayout() propertyTab.minMaxCheckBox = QCheckBox() propertyTab.minMaxCheckBox.setCheckable(True) connector1 = partial(self.main_window.toggleUserMinMax, property=property_kind) propertyTab.minMaxCheckBox.stateChanged.connect(connector1) propertyTab.minBox = ScientificDoubleSpinBox(self) propertyTab.minBox.setMaximum(1E9) propertyTab.minBox.setMinimum(0) propertyTab.maxBox = ScientificDoubleSpinBox(self) propertyTab.maxBox.setMaximum(1E9) propertyTab.maxBox.setMinimum(0) connector2 = partial(self.main_window.editColorbarMin, property_type=property_kind) propertyTab.minBox.valueChanged.connect(connector2) connector3 = partial(self.main_window.editColorbarMax, property_type=property_kind) propertyTab.maxBox.valueChanged.connect(connector3) propertyTab.colormapBox = QComboBox(self) cmaps = sorted(m for m in mcolormaps.datad if not m.endswith("_r")) for cmap in cmaps: propertyTab.colormapBox.addItem(cmap) connector = partial(self.main_window.editColorMap, property_type=property_kind) propertyTab.colormapBox.currentTextChanged[str].connect(connector) propertyTab.dataIndicatorCheckBox = QCheckBox() propertyTab.dataIndicatorCheckBox.setCheckable(True) connector4 = partial(self.main_window.toggleDataIndicatorCheckBox, property=property_kind) propertyTab.dataIndicatorCheckBox.stateChanged.connect(connector4) propertyTab.colorBarScaleCheckBox = QCheckBox() propertyTab.colorBarScaleCheckBox.setCheckable(True) connector5 = partial(self.main_window.toggleColorbarScale, property=property_kind) propertyTab.colorBarScaleCheckBox.stateChanged.connect(connector5) formLayout = QFormLayout() formLayout.setAlignment(QtCore.Qt.AlignHCenter) formLayout.setFormAlignment(QtCore.Qt.AlignHCenter) formLayout.setLabelAlignment(QtCore.Qt.AlignLeft) formLayout.addRow('Colormap:', propertyTab.colormapBox) formLayout.addRow('Custom Min/Max', propertyTab.minMaxCheckBox) formLayout.addRow('Data Indicator', propertyTab.dataIndicatorCheckBox) formLayout.addRow('Log Scale', propertyTab.colorBarScaleCheckBox) formLayout.addRow(HorizontalLine()) formLayout.addRow('Max: ', propertyTab.maxBox) formLayout.addRow('Min: ', propertyTab.minBox) propertyTab.setLayout(formLayout) return propertyTab
def __init__(self): super(Window, self).__init__() self.proxyModel = QSortFilterProxyModel() self.proxyModel.setDynamicSortFilter(True) self.sourceGroupBox = QGroupBox("Original Model") self.proxyGroupBox = QGroupBox("Sorted/Filtered Model") self.sourceView = QTreeView() self.sourceView.setRootIsDecorated(False) self.sourceView.setAlternatingRowColors(True) self.proxyView = QTreeView() self.proxyView.setRootIsDecorated(False) self.proxyView.setAlternatingRowColors(True) self.proxyView.setModel(self.proxyModel) self.proxyView.setSortingEnabled(True) self.sortCaseSensitivityCheckBox = QCheckBox("Case sensitive sorting") self.filterCaseSensitivityCheckBox = QCheckBox("Case sensitive filter") self.filterPatternLineEdit = QLineEdit() self.filterPatternLineEdit.setClearButtonEnabled(True) self.filterPatternLabel = QLabel("&Filter pattern:") self.filterPatternLabel.setBuddy(self.filterPatternLineEdit) self.filterSyntaxComboBox = QComboBox() self.filterSyntaxComboBox.addItem("Regular expression", REGULAR_EXPRESSION) self.filterSyntaxComboBox.addItem("Wildcard", WILDCARD) self.filterSyntaxComboBox.addItem("Fixed string", FIXED_STRING) self.filterSyntaxLabel = QLabel("Filter &syntax:") self.filterSyntaxLabel.setBuddy(self.filterSyntaxComboBox) self.filterColumnComboBox = QComboBox() self.filterColumnComboBox.addItem("Subject") self.filterColumnComboBox.addItem("Sender") self.filterColumnComboBox.addItem("Date") self.filterColumnLabel = QLabel("Filter &column:") self.filterColumnLabel.setBuddy(self.filterColumnComboBox) self.filterPatternLineEdit.textChanged.connect(self.filterRegExpChanged) self.filterSyntaxComboBox.currentIndexChanged.connect(self.filterRegExpChanged) self.filterColumnComboBox.currentIndexChanged.connect(self.filterColumnChanged) self.filterCaseSensitivityCheckBox.toggled.connect(self.filterRegExpChanged) self.sortCaseSensitivityCheckBox.toggled.connect(self.sortChanged) sourceLayout = QHBoxLayout() sourceLayout.addWidget(self.sourceView) self.sourceGroupBox.setLayout(sourceLayout) proxyLayout = QGridLayout() proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3) proxyLayout.addWidget(self.filterPatternLabel, 1, 0) proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1, 1, 2) proxyLayout.addWidget(self.filterSyntaxLabel, 2, 0) proxyLayout.addWidget(self.filterSyntaxComboBox, 2, 1, 1, 2) proxyLayout.addWidget(self.filterColumnLabel, 3, 0) proxyLayout.addWidget(self.filterColumnComboBox, 3, 1, 1, 2) proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 4, 0, 1, 2) proxyLayout.addWidget(self.sortCaseSensitivityCheckBox, 4, 2) self.proxyGroupBox.setLayout(proxyLayout) mainLayout = QVBoxLayout() mainLayout.addWidget(self.sourceGroupBox) mainLayout.addWidget(self.proxyGroupBox) self.setLayout(mainLayout) self.setWindowTitle("Basic Sort/Filter Model") self.resize(500, 450) self.proxyView.sortByColumn(1, Qt.AscendingOrder) self.filterColumnComboBox.setCurrentIndex(1) self.filterPatternLineEdit.setText("Andy|Grace") self.filterCaseSensitivityCheckBox.setChecked(True) self.sortCaseSensitivityCheckBox.setChecked(True)