class ChangeConfLevelDlg(QDialog): ''' Dialog for changing confidence level ''' def __init__(self, previous_value=DEFAULT_CONF_LEVEL, parent=None): super(ChangeConfLevelDlg, self).__init__(parent) cl_label = QLabel("Global Confidence Level:") self.conf_level_spinbox = QDoubleSpinBox() self.conf_level_spinbox.setRange(50, 99.999 ) self.conf_level_spinbox.setSingleStep(0.1) self.conf_level_spinbox.setSuffix(QString("%")) self.conf_level_spinbox.setValue(previous_value) self.conf_level_spinbox.setDecimals(1) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) hlayout = QHBoxLayout() hlayout.addWidget(cl_label) hlayout.addWidget(self.conf_level_spinbox) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(buttonBox) self.setLayout(vlayout) self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()")) self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()")) self.setWindowTitle("Change Confidence Level") def get_value(self): return self.conf_level_spinbox.value()
class ChangeConfLevelDlg(QDialog): ''' Dialog for changing confidence level ''' def __init__(self, previous_value=DEFAULT_CONF_LEVEL, parent=None): super(ChangeConfLevelDlg, self).__init__(parent) cl_label = QLabel("Global Confidence Level:") self.conf_level_spinbox = QDoubleSpinBox() self.conf_level_spinbox.setRange(50, 99.999) self.conf_level_spinbox.setSingleStep(0.1) self.conf_level_spinbox.setSuffix(QString("%")) self.conf_level_spinbox.setValue(previous_value) self.conf_level_spinbox.setDecimals(1) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) hlayout = QHBoxLayout() hlayout.addWidget(cl_label) hlayout.addWidget(self.conf_level_spinbox) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(buttonBox) self.setLayout(vlayout) self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()")) self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()")) self.setWindowTitle("Change Confidence Level") def get_value(self): return self.conf_level_spinbox.value()
def _refresh_widgets_from_axistags(self): axiskeys = [tag.key for tag in self.axistags] row_widgets = collections.OrderedDict() for key in axiskeys: tag_info = self.axistags[key] resolution_box = QDoubleSpinBox(parent=self) resolution_box.setRange(0.0, numpy.finfo(numpy.float32).max) resolution_box.setValue(tag_info.resolution) resolution_box.valueChanged.connect( self._update_axistags_from_widgets) resolution_box.installEventFilter(self) description_edit = QLineEdit(tag_info.description, parent=self) description_edit.textChanged.connect( self._update_axistags_from_widgets) description_edit.installEventFilter(self) row_widgets[key] = RowWidgets(resolution_box, description_edit) # Clean up old widgets (if any) for row in range(self.rowCount()): for col in range(self.columnCount()): w = self.cellWidget(row, col) if w: w.removeEventFilter(self) # Fill table with widgets self.setRowCount(len(row_widgets)) self.setVerticalHeaderLabels(row_widgets.keys()) for row, widgets in enumerate(row_widgets.values()): self.setCellWidget(row, 0, widgets.resolution_box) self.setCellWidget(row, 1, widgets.description_edit)
class AbstractSnappingToleranceAction(QWidgetAction): """Abstract action for Snapping Tolerance.""" snappingToleranceChanged = pyqtSignal(float) def __init__(self, parent=None): super(AbstractSnappingToleranceAction, self).__init__(parent) self._iface = None self._toleranceSpin = QDoubleSpinBox(parent) self._toleranceSpin.setDecimals(5) self._toleranceSpin.setRange(0.0, 100000000.0) self.setDefaultWidget(self._toleranceSpin) self.setText('Snapping Tolerance') self.setStatusTip('Set the snapping tolerance') self._refresh() self._toleranceSpin.valueChanged.connect(self._changed) def setInterface(self, iface): self._iface = iface self._refresh() # Private API def _changed(self, tolerance): pass def _refresh(self): pass
def _refresh_widgets_from_axistags(self): axiskeys = [tag.key for tag in self.axistags] row_widgets = collections.OrderedDict() for key in axiskeys: tag_info = self.axistags[key] resolution_box = QDoubleSpinBox(parent=self) resolution_box.setRange(0.0, numpy.finfo(numpy.float32).max) resolution_box.setValue( tag_info.resolution ) resolution_box.valueChanged.connect( self._update_axistags_from_widgets ) resolution_box.installEventFilter(self) description_edit = QLineEdit(tag_info.description, parent=self) description_edit.textChanged.connect( self._update_axistags_from_widgets ) description_edit.installEventFilter(self) row_widgets[key] = RowWidgets( resolution_box, description_edit ) # Clean up old widgets (if any) for row in range(self.rowCount()): for col in range(self.columnCount()): w = self.cellWidget( row, col ) if w: w.removeEventFilter(self) # Fill table with widgets self.setRowCount( len(row_widgets) ) self.setVerticalHeaderLabels( row_widgets.keys() ) for row, widgets in enumerate(row_widgets.values()): self.setCellWidget( row, 0, widgets.resolution_box ) self.setCellWidget( row, 1, widgets.description_edit )
def initUI(self): self.grid = QGridLayout(self) self.setLayout(self.grid) self.loadSettings() self.inputLabels = [QLabel(l) for l in self.Inputs] self.inputBoxes = [] for i, iL in enumerate(self.inputLabels): self.grid.addWidget(iL, i, 0) sp = QDoubleSpinBox(self) sp.setRange(-1e10, 1e10) sp.setKeyboardTracking(False) self.grid.addWidget(sp, i, 1) self.inputBoxes.append(sp) for val, iB in zip(self.inputValues, self.inputBoxes): iB.setValue(val) self.connectSpinBoxes() self.outputValues = [0.0]*len(self.Outputs) self.outputLabels = [QLabel(l) for l in self.Outputs] self.outputValueLabels = [QLabel('0.0') for l in self.Outputs] sI = len(self.inputLabels) for i, oL in enumerate(self.outputLabels): self.grid.addWidget(oL, sI + i, 0) self.grid.addWidget(self.outputValueLabels[i], sI + i, 1)
def _create(self, base_frame): self.sliders = [] self.spinboxes = [] for i in range(len(self.dim_labels)): self.sliders.append(QSlider(QtCore.Qt.Horizontal)) self.sliders[i].setRange(0, self.n_slider_steps[i]) self.sliders[i].valueChanged.connect( partial(self._on_slide, i)) spinbox = QDoubleSpinBox() spinbox.setRange(*self.limits[i]) spinbox.setDecimals(3) spinbox.setSingleStep(0.001) self.spinboxes.append(spinbox) self.spinboxes[i].valueChanged.connect( partial(self._on_pos_edited, i)) slider_group = QGridLayout() slider_group.addWidget(QLabel("Position"), 0, 0, 1, 3, QtCore.Qt.AlignCenter) slider_group.addWidget(QLabel("Orientation (Euler angles)"), 0, 3, 1, 3, QtCore.Qt.AlignCenter) for i, slider in enumerate(self.sliders): slider_group.addWidget(QLabel(self.dim_labels[i]), 1, i) slider_group.addWidget(slider, 2, i) slider_group.addWidget(self.spinboxes[i], 3, i) slider_groupbox = QGroupBox("Transformation in frame '%s'" % base_frame) slider_groupbox.setLayout(slider_group) layout = QHBoxLayout() layout.addWidget(slider_groupbox) layout.addStretch(1) return layout
def float_widget(self, start_val, min_val, max_val, step): """ Returns a float widget with the given values. """ box = QDoubleSpinBox() box.setRange(min_val, max_val) box.setValue(start_val) box.setSingleStep(step) return box
def createDoubleSpinner(self, minimum, maximum): spinner = QDoubleSpinBox() spinner.setEnabled(False) spinner.setMinimumWidth(75) spinner.setRange(minimum, maximum) spinner.setKeyboardTracking(False) spinner.editingFinished.connect(self.spinning) spinner.valueChanged.connect(self.spinning) return spinner
def __createDoubleSpinner(self): spinner = QDoubleSpinBox() spinner.setEnabled(False) spinner.setMinimumWidth(75) max = 999999999999 spinner.setRange(-max,max) # spinner.valueChanged.connect(self.plotScalesChanged) spinner.editingFinished.connect(self.plotScalesChanged) return spinner
class LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip(_( "If checked, Frescobaldi will not shorten filenames in the log output.""")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace")) font.setPointSizeF(float(s.value("fontsize", 9.0))) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True) not in (False, "false")) self.rawview.setChecked(s.value("rawview", True) not in (False, "false")) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked())
def createEditor( self, parent, _option, index ): if index.column() == ABONO: spinbox = QDoubleSpinBox( parent ) max = index.model().lines[index.row()].totalFac spinbox.setRange( 0.0001, max ) spinbox.setDecimals( 4 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox else: None
def createDoubleSpinner(self, minimum, maximum): spinner = QDoubleSpinBox() spinner.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) spinner.setMinimumWidth(105) spinner.setRange(minimum, maximum) spinner.setKeyboardTracking(False) spinner.setDecimals(8) spinner.editingFinished.connect(self.plotScaleChanged) spinner.valueChanged.connect(self.plotScaleChanged) return spinner
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.label_amount = QLabel('Amount') self.spin_amount = QDoubleSpinBox() self.spin_amount.setRange(0, 10000000000) self.spin_amount.setPrefix('Rp. ') self.spin_amount.setSingleStep(100000) self.label_rate = QLabel('Rate') self.spin_rate = QDoubleSpinBox() self.spin_rate.setSuffix(' %') self.spin_rate.setSingleStep(0.1) self.spin_rate.setRange(0, 100) self.label_year = QLabel('Years') self.spin_year = QSpinBox() self.spin_year.setSuffix(' year') self.spin_year.setSingleStep(1) self.spin_year.setRange(0, 1000) self.spin_year.setValue(1) self.label_total_ = QLabel('Total') self.label_total = QLabel('Rp. 0.00') grid = QGridLayout() grid.addWidget(self.label_amount, 0, 0) grid.addWidget(self.spin_amount, 0, 1) grid.addWidget(self.label_rate, 1, 0) grid.addWidget(self.spin_rate, 1, 1) grid.addWidget(self.label_year, 2, 0) grid.addWidget(self.spin_year, 2, 1) grid.addWidget(self.label_total_, 3, 0) grid.addWidget(self.label_total, 3, 1) self.setLayout(grid) self.connect(self.spin_amount, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_rate, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_year, SIGNAL('valueChanged(int)'), self.update_ui) self.setWindowTitle('Interest') def update_ui(self): amount = self.spin_amount.value() rate = self.spin_rate.value() year = self.spin_year.value() total = amount * (1 + rate / 100.0)**year self.label_total.setText('Rp. %.2f' % total)
def widgetByType(self, valueType): if isinstance(valueType, str): valPieces = valueType.lower().split(":") typeStr = valPieces[0] rngMin = "min" rngMax = "max" if len(valPieces) == 3: rngMin = valPieces[1] if valPieces[1] != "" else "min" rngMax = valPieces[2] if valPieces[2] != "" else "max" if typeStr == "float": box = QDoubleSpinBox(self) if rngMin == "min": rngMin = -2000000000. else: rngMin = float(rngMin) if rngMax == "max": rngMax = 2000000000. else: rngMax = float(rngMax) box.setRange(rngMin, rngMax) box.setDecimals(10) return box elif typeStr == "int": box = QSpinBox(self) if rngMin == "min": rngMin = -2**31 + 1 else: rngMin = int(rngMin) if rngMax == "max": rngMax = 2**31 - 1 else: rngMax = int(rngMax) box.setRange(rngMin, rngMax) return box elif typeStr == "str": return QLineEdit(self) elif typeStr == "bool": return QCheckBox(self) elif isinstance(valueType, list): box = QComboBox(self) for item in valueType: box.addItem(item) return box
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) principalLabel = QLabel("Principal:") self.principalSpinBox = QDoubleSpinBox() self.principalSpinBox.setRange(1, 1000000000) self.principalSpinBox.setValue(1000) self.principalSpinBox.setPrefix("$ ") rateLabel = QLabel("Rate:") self.rateSpinBox = QDoubleSpinBox() self.rateSpinBox.setRange(1, 100) self.rateSpinBox.setValue(5) self.rateSpinBox.setSuffix(" %") yearsLabel = QLabel("Years:") self.yearsComboBox = QComboBox() self.yearsComboBox.addItem("1 year") self.yearsComboBox.addItems( ["{0} years".format(x) for x in range(2, 26)]) amountLabel = QLabel("Amount") self.amountLabel = QLabel() grid = QGridLayout() grid.addWidget(principalLabel, 0, 0) grid.addWidget(self.principalSpinBox, 0, 1) grid.addWidget(rateLabel, 1, 0) grid.addWidget(self.rateSpinBox, 1, 1) grid.addWidget(yearsLabel, 2, 0) grid.addWidget(self.yearsComboBox, 2, 1) grid.addWidget(amountLabel, 3, 0) grid.addWidget(self.amountLabel, 3, 1) self.setLayout(grid) self.connect(self.principalSpinBox, SIGNAL("valueChanged(double)"), self.updateUi) self.connect(self.rateSpinBox, SIGNAL("valueChanged(double)"), self.updateUi) self.connect(self.yearsComboBox, SIGNAL("currentIndexChanged(int)"), self.updateUi) self.setWindowTitle("Interest") self.updateUi() def updateUi(self): """Calculates compound interest""" principal = self.principalSpinBox.value() rate = self.rateSpinBox.value() years = self.yearsComboBox.currentIndex() + 1 amount = principal * ((1 + (rate / 100.0))**years) self.amountLabel.setText("$ {0:.2f}".format(amount))
def add_layer(self): i = self.dlg.table.rowCount() self.dlg.table.insertRow(i) layer = QgsMapLayerComboBox() layer.setFilters(QgsMapLayerProxyModel.RasterLayer) band = QTableWidgetItem('1') band.setFlags(Qt.ItemIsEnabled) mean = QDoubleSpinBox() mean.setRange(-10000.00,10000.00) self.dlg.table.setCellWidget(i, 0, layer) self.dlg.table.setItem(i, 1, band) self.dlg.table.setCellWidget(i, 2, mean)
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.label_amount = QLabel('Amount') self.spin_amount = QDoubleSpinBox() self.spin_amount.setRange(0, 10000000000) self.spin_amount.setPrefix('Rp. ') self.spin_amount.setSingleStep(100000) self.label_rate = QLabel('Rate') self.spin_rate = QDoubleSpinBox() self.spin_rate.setSuffix(' %') self.spin_rate.setSingleStep(0.1) self.spin_rate.setRange(0, 100) self.label_year = QLabel('Years') self.spin_year = QSpinBox() self.spin_year.setSuffix(' year') self.spin_year.setSingleStep(1) self.spin_year.setRange(0, 1000) self.spin_year.setValue(1) self.label_total_ = QLabel('Total') self.label_total = QLabel('Rp. 0.00') grid = QGridLayout() grid.addWidget(self.label_amount, 0, 0) grid.addWidget(self.spin_amount, 0, 1) grid.addWidget(self.label_rate, 1, 0) grid.addWidget(self.spin_rate, 1, 1) grid.addWidget(self.label_year, 2, 0) grid.addWidget(self.spin_year, 2, 1) grid.addWidget(self.label_total_, 3, 0) grid.addWidget(self.label_total, 3, 1) self.setLayout(grid) self.connect(self.spin_amount, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_rate, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_year, SIGNAL('valueChanged(int)'), self.update_ui) self.setWindowTitle('Interest') def update_ui(self): amount = self.spin_amount.value() rate = self.spin_rate.value() year = self.spin_year.value() total = amount * (1 + rate / 100.0) ** year self.label_total.setText('Rp. %.2f' % total)
def add_layer(self): i = self.dlg.table.rowCount() self.dlg.table.insertRow(i) layer = QgsMapLayerComboBox() layer.setFilters(QgsMapLayerProxyModel.RasterLayer) band = QTableWidgetItem('1') band.setFlags(Qt.ItemIsEnabled) mean = QDoubleSpinBox() mean.setRange(-10000.00, 10000.00) self.dlg.table.setCellWidget(i, 0, layer) self.dlg.table.setItem(i, 1, band) self.dlg.table.setCellWidget(i, 2, mean)
def populateGuessBoxes(self): self.guessBox = [] self.fitBox = [] sI = 1 # TODO: do something smart about this for i, n in enumerate(self.fitter.parameterNames): spGuess = QDoubleSpinBox(self) spGuess.setRange(-1e10, 1e10) spGuess.setKeyboardTracking(False) spFit = QLabel('0.0') self.parmGrid.addWidget(QLabel(n, parent=self), i+sI+1, 0) self.parmGrid.addWidget(spGuess, i+sI+1, 1) self.parmGrid.addWidget(spFit, i+sI+1, 2) self.guessBox.append(spGuess) self.fitBox.append(spFit) self.connectGuessBoxes()
class CharMap(preferences.Group): def __init__(self, page): super(CharMap, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) app.translateUI(self) def translateUI(self): self.setTitle(_("Special Characters")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("charmaptool") font = self.font() family = s.value("fontfamily", "", type("")) if family: font.setFamily(family) font.setPointSizeF(s.value("fontsize", font.pointSizeF(), float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) def saveSettings(self): s = QSettings() s.beginGroup("charmaptool") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class CharMap(preferences.Group): def __init__(self, page): super(CharMap, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) app.translateUI(self) def translateUI(self): self.setTitle(_("Special Characters")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("charmaptool") font = self.font() family = s.value("fontfamily", "") if family: font.setFamily(family) font.setPointSizeF(float(s.value("fontsize", font.pointSizeF()))) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) def saveSettings(self): s = QSettings() s.beginGroup("charmaptool") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
def nextWidget(self): self.buttonNext.setEnabled(False) self.buttonBack.setEnabled(True) self.stackedWidget.setCurrentIndex(1) self.widgetExperiment.tableWidget.clear() self.widgetExperiment.memoryEdit.clear() self.widgetExperiment.signalEdit.clear() self.widgetExperiment.outputEdit.clear() self.widgetExperiment.tableWidget.setRowCount(self.widgetInputCount.spinInput.value()) self.widgetExperiment.tableWidget.setColumnCount(3) self.widgetExperiment.tableWidget.setHorizontalHeaderLabels(['i', 'w(i)', 'x(i)']) self.neuron = Neuron(self.widgetInputCount.spinInput.value()) for i in xrange(len(self.neuron.weights)): spinBox1 = QDoubleSpinBox() spinBox1.setRange(-100.0, 100.0) spinBox2 = QDoubleSpinBox() spinBox2.setRange(-100.0, 100.0) self.connect(spinBox1, SIGNAL('valueChanged(double)'), self.updateResult) self.connect(spinBox2, SIGNAL('valueChanged(double)'), self.updateResult) self.widgetExperiment.tableWidget.setCellWidget(i, 0, QLabel(str(i + 1))) self.widgetExperiment.tableWidget.setCellWidget(i, 1, spinBox1) self.widgetExperiment.tableWidget.setCellWidget(i, 2, spinBox2)
class ModifyPickerPropertiesMenu(QDialog): def __init__(self, data, win_parent=None): self.win_parent = win_parent self._size = data['size'] * 100. self.out_data = data self.dim_max = data['dim_max'] QDialog.__init__(self, win_parent) self.setWindowTitle('Modify Picker Properties') self.create_widgets() self.create_layout() self.set_connections() width = 260 height = 130 self.resize(width, height) #self.show() def create_widgets(self): # Size self.size = QLabel("Percent of Screen Size:") self.size_edit = QDoubleSpinBox(self) self.size_edit.setRange(0., 10.) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(3, decimals) self.size_edit.setDecimals(decimals) self.size_edit.setSingleStep(10. / 5000.) self.size_edit.setValue(self._size) # closing #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") def create_layout(self): grid = QGridLayout() grid.addWidget(self.size, 1, 0) grid.addWidget(self.size_edit, 1, 1) ok_cancel_box = QHBoxLayout() #ok_cancel_box.addWidget(self.apply_button) #ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox) self.layout() #def on_color(self): #pass def set_connections(self): self.size_edit.valueChanged.connect(self.on_size) if qt_version == 4: self.connect(self.size_edit, QtCore.SIGNAL('editingFinished()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('valueChanged()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('clicked()'), self.on_size) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.size_edit.editingFinished.connect(self.on_size) self.size_edit.valueChanged.connect(self.on_size) ## ??? clicked self.cancel_button.clicked.connect(self.on_cancel) #self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.out_data['close'] = True event.accept() def on_size(self): self._size = float(self.size_edit.text()) self.on_apply(force=True) @staticmethod def check_float(cell): text = cell.text() value = float(text) return value, True def on_validate(self): size_value, flag0 = self.check_float(self.size_edit) if flag0: self._size = size_value #self.out_data['min'] = min(min_value, max_value) #self.out_data['max'] = max(min_value, max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self, force=False): passed = self.on_validate() if (passed or Force) and self.win_parent is not None: self.win_parent.element_picker_size = self._size / 100. return passed def on_ok(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False self.out_data['close'] = True passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['clicked_cancel'] = True self.out_data['close'] = True self.close()
class LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) self.hideauto = QCheckBox(toggled=self.changed) layout.addWidget(self.hideauto) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip( _("If checked, Frescobaldi will not shorten filenames in the log output." "")) self.hideauto.setText(_("Hide automatic engraving jobs")) self.hideauto.setToolTip( _("If checked, Frescobaldi will not show the log for automatically\n" "started engraving jobs (LilyPond->Auto-engrave).")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace", type(""))) font.setPointSizeF(s.value("fontsize", 9.0, float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True, bool)) self.rawview.setChecked(s.value("rawview", True, bool)) self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked()) s.setValue("hide_auto_engrave", self.hideauto.isChecked())
class GeoLocationWidget(QWidget): """GeoLocationWidget(QWidget) Provides a custom geographical location widget. """ __pyqtSignals__ = ("latitudeChanged(double)", "longitudeChanged(double)", "elevationChanged(double)") def __init__(self, parent=None): super().__init__(parent) latitudeLabel = QLabel(self.tr("Latitude:")) self.latitudeSpinBox = QDoubleSpinBox() self.latitudeSpinBox.setRange(-90.0, 90.0) self.latitudeSpinBox.setDecimals(5) self.latitudeSpinBox.setSuffix(" degrees") self.latitudeSpinBox.setToolTip( "How far north or sourth you are from the equator. Must be between -90 and 90." ) longitudeLabel = QLabel(self.tr("Longitude:")) self.longitudeSpinBox = QDoubleSpinBox() self.longitudeSpinBox.setRange(-180.0, 180.0) self.longitudeSpinBox.setDecimals(5) self.longitudeSpinBox.setSuffix(" degrees") self.longitudeSpinBox.setToolTip( "How far west or east you are from the meridian. Must be between -180 and 180." ) elevationLabel = QLabel(self.tr("Elevation")) self.elevationSpinBox = QDoubleSpinBox() self.elevationSpinBox.setRange(-418.0, 8850.0) self.elevationSpinBox.setDecimals(5) self.elevationSpinBox.setSuffix(" m") self.elevationSpinBox.setToolTip( "The distance from sea level in meters. Must be between -418 and 8850." ) self.connect(self.latitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("latitudeChanged(double)")) self.connect(self.longitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("longitudeChanged(double)")) self.connect(self.elevationSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("elevationChanged(double)")) layout = QGridLayout(self) layout.addWidget(latitudeLabel, 0, 0) layout.addWidget(self.latitudeSpinBox, 1, 0) layout.addWidget(longitudeLabel, 0, 1) layout.addWidget(self.longitudeSpinBox, 1, 1) layout.addWidget(elevationLabel, 0, 2) layout.addWidget(self.elevationSpinBox, 1, 2) # The latitude property is implemented with the latitude() and setLatitude() # methods, and contains the latitude of the user. def latitude(self): return self.latitudeSpinBox.value() @pyqtSignature("setLatitude(double)") def setLatitude(self, latitude): if latitude != self.latitudeSpinBox.value(): self.latitudeSpinBox.setValue(latitude) self.emit(SIGNAL("latitudeChanged(double)"), latitude) latitude = pyqtProperty("double", latitude, setLatitude) # The longitude property is implemented with the longitude() and setlongitude() # methods, and contains the longitude of the user. def longitude(self): return self.longitudeSpinBox.value() @pyqtSignature("setLongitude(double)") def setLongitude(self, longitude): if longitude != self.longitudeSpinBox.value(): self.longitudeSpinBox.setValue(longitude) self.emit(SIGNAL("longitudeChanged(double)"), longitude) longitude = pyqtProperty("double", longitude, setLongitude) def elevation(self): return self.elevationSpinBox.value() @pyqtSignature("setElevation(double)") def setElevation(self, elevation): if elevation != self.elevationSpinBox.value(): self.elevationSpinBox.setValue(elevation) self.emit(SIGNAL("elevationChanged(double)"), elevation) elevation = pyqtProperty("double", elevation, setElevation)
class OrbitCorrGeneral(QtGui.QWidget): """ A general orbit correction or local bump panel. """ def __init__(self, bpms, cors, parent = None): super(OrbitCorrGeneral, self).__init__(parent) self.bpms, self.cors = bpms, cors self.sb = [bpm.sb for bpm in self.bpms] self.x0, self.y0 = None, None self._update_current_orbit() self.table = QTableWidget(len(self.bpms), 9) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) hdview = QHeaderView(Qt.Horizontal) self.table.setHorizontalHeaderLabels( ['BPM Name', 's', "Beta X", "Beta Y", "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"]) self._twiss = getTwiss([b.name for b in self.bpms], ["s", "betax", "betay", "etax"]) for i,bpm in enumerate(self.bpms): it = QTableWidgetItem(bpm.name) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) self.table.setItem(i, 0, it) it = QTableWidgetItem(str(bpm.sb)) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) #it.setMinimumWidth(80) self.table.setItem(i, 1, it) self.table.setItem(i, 2, QTableWidgetItem("%.4f" % self._twiss[i,1])) self.table.setItem(i, 3, QTableWidgetItem("%.4f" % self._twiss[i,2])) self.table.setItem(i, 4, QTableWidgetItem("%.4f" % self._twiss[i,3])) for j in range(5, 9): it = QTableWidgetItem(str(0.0)) it.setData(Qt.DisplayRole, str(0.0)) it.setFlags(it.flags() | Qt.ItemIsEditable) self.table.setItem(i, j, it) # use the current orbit #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i])) #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i])) #self.connect(self.table, SIGNAL("cellClicked(int, int)"), # self._cell_clicked) self.table.resizeColumnsToContents() #self.table.horizontalHeader().setStretchLastSection(True) #for i in range(4): # print "width", i, self.table.columnWidth(i) #self.table.setColumnWidth(0, 300) self.table.setColumnWidth(1, 80) vbox1 = QtGui.QVBoxLayout() frmbox = QFormLayout() self.base_orbit_box = QtGui.QComboBox() #self.base_orbit_box.addItems([ # "Current Orbit", "All Zeros"]) self.base_orbit_box.addItems(["All Zeros", "Current Orbit"]) frmbox.addRow("Orbit Base", self.base_orbit_box) grp = QtGui.QGroupBox("Local Bump") grp.setLayout(frmbox) vbox1.addWidget(grp) frmbox = QFormLayout() hln1 = QtGui.QFrame() hln1.setLineWidth(3) hln1.setFrameStyle(QtGui.QFrame.Sunken) hln1.setFrameShape(QtGui.QFrame.HLine) frmbox.addRow(hln1) self.repeatbox = QSpinBox() self.repeatbox.setRange(1, 20) self.repeatbox.setValue(3) # or connect the returnPressed() signal frmbox.addRow("&Repeat correction", self.repeatbox) self.rcondbox = QLineEdit() self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self)) self.rcondbox.setText("1e-2") frmbox.addRow("r&cond for SVD", self.rcondbox) self.scalebox = QDoubleSpinBox() self.scalebox.setRange(0.01, 5.00) self.scalebox.setSingleStep(0.01) self.scalebox.setValue(0.68) frmbox.addRow("&Scale correctors", self.scalebox) #hln2 = QtGui.QFrame() #hln2.setLineWidth(3) #hln2.setFrameStyle(QtGui.QFrame.Sunken) #hln2.setFrameShape(QtGui.QFrame.HLine) #frmbox.addRow(hln2) self.progress = QProgressBar() self.progress.setMaximum(self.repeatbox.value()) self.progress.setMaximumHeight(15) frmbox.addRow("Progress", self.progress) grp = QtGui.QGroupBox("Correction") grp.setLayout(frmbox) vbox1.addWidget(grp) #vbox.addStretch(1.0) #self.qdb = QDialogButtonBox(self) #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole) #self.qdb.addButton("R", QDialogButtonBox.ResetRole) #btn.setDefault(True) #self.qdb.addButton(QDialogButtonBox.Cancel) #self.qdb.addButton(QDialogButtonBox.Help) gbox = QtGui.QGridLayout() btn = QPushButton("Clear") self.connect(btn, SIGNAL("clicked()"), self.resetBumps) gbox.addWidget(btn, 0, 1) self.correctOrbitBtn = QPushButton("Apply") #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }"); self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply) self.correctOrbitBtn.setDefault(True) gbox.addWidget(self.correctOrbitBtn, 1, 1) gbox.setColumnStretch(0, 1) vbox1.addStretch() vbox1.addLayout(gbox) hbox1 = QtGui.QHBoxLayout() hbox1.addWidget(self.table, 2) hbox1.addLayout(vbox1, 0) self.setLayout(hbox1) self.connect(self.base_orbit_box, SIGNAL("currentIndexChanged(QString)"), self.updateTargetOrbit) self.connect(self.repeatbox, SIGNAL("valueChanged(int)"), self.progress.setMaximum) self.connect(self.table, SIGNAL("cellChanged (int, int)"), self.updateBump) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def _update_current_orbit(self): pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms] pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms] self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)] self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)] def resetBumps(self): jx0, jy0 = 5, 6 for i in range(self.table.rowCount()): self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0)) self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0)) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def call_apply(self): #print "apply the orbit" obt = [] jx, jy = 7, 8 for i in range(self.table.rowCount()): x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat() y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat() obt.append([x1, y1]) self.correctOrbitBtn.setEnabled(False) nrepeat = self.repeatbox.value() kw = { "scale": float(self.scalebox.text()), "rcond": float(self.rcondbox.text()) } self.progress.setValue(0) QApplication.processEvents() for i in range(nrepeat): err, msg = setLocalBump(self.bpms, self.cors, obt, **kw) self.progress.setValue(i+1) QApplication.processEvents() if err != 0: QtGui.QMessageBox.critical( self, "Local Orbit Bump", "ERROR: {0}\nAbort.".format(msg), QtGui.QMessageBox.Ok) #self.progress.setValue(0) break self.correctOrbitBtn.setEnabled(True) def getTargetOrbit(self): x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] return (self.sb, x), (self.sb, y) def updateTargetOrbit(self, baseobt): if baseobt == "All Zeros": jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): it0 = self.table.item(i, jx0) it1 = self.table.item(i, jx1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) it0 = self.table.item(i, jy0) it1 = self.table.item(i, jy1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) elif baseobt == "Current Orbit": self._update_current_orbit() jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jx1) it.setData(Qt.DisplayRole, self.x0[i] + dx0) dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jy1) it.setData(Qt.DisplayRole, self.y0[i] + dy0) #self._update_orbit_plot() x, y = self.getTargetOrbit() self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"), x, y) def updateBump(self, row, col): #print "updating ", row, col if col == 5 or col == 6: self.updateTargetOrbit(self.base_orbit_box.currentText())
class GeoLocationWidget(QWidget): """GeoLocationWidget(QWidget) Provides a custom geographical location widget. """ __pyqtSignals__ = ("latitudeChanged(double)", "longitudeChanged(double)", "elevationChanged(double)") def __init__(self, parent = None): super().__init__(parent) latitudeLabel = QLabel(self.tr("Latitude:")) self.latitudeSpinBox = QDoubleSpinBox() self.latitudeSpinBox.setRange(-90.0, 90.0) self.latitudeSpinBox.setDecimals(5) self.latitudeSpinBox.setSuffix(" degrees") self.latitudeSpinBox.setToolTip("How far north or sourth you are from the equator. Must be between -90 and 90.") longitudeLabel = QLabel(self.tr("Longitude:")) self.longitudeSpinBox = QDoubleSpinBox() self.longitudeSpinBox.setRange(-180.0, 180.0) self.longitudeSpinBox.setDecimals(5) self.longitudeSpinBox.setSuffix(" degrees") self.longitudeSpinBox.setToolTip("How far west or east you are from the meridian. Must be between -180 and 180.") elevationLabel = QLabel(self.tr("Elevation")) self.elevationSpinBox = QDoubleSpinBox() self.elevationSpinBox.setRange(-418.0, 8850.0) self.elevationSpinBox.setDecimals(5) self.elevationSpinBox.setSuffix(" m") self.elevationSpinBox.setToolTip("The distance from sea level in meters. Must be between -418 and 8850.") self.connect(self.latitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("latitudeChanged(double)")) self.connect(self.longitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("longitudeChanged(double)")) self.connect(self.elevationSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("elevationChanged(double)")) layout = QGridLayout(self) layout.addWidget(latitudeLabel, 0, 0) layout.addWidget(self.latitudeSpinBox, 1, 0) layout.addWidget(longitudeLabel, 0, 1) layout.addWidget(self.longitudeSpinBox, 1, 1) layout.addWidget(elevationLabel, 0, 2) layout.addWidget(self.elevationSpinBox, 1, 2) # The latitude property is implemented with the latitude() and setLatitude() # methods, and contains the latitude of the user. def latitude(self): return self.latitudeSpinBox.value() @pyqtSignature("setLatitude(double)") def setLatitude(self, latitude): if latitude != self.latitudeSpinBox.value(): self.latitudeSpinBox.setValue(latitude) self.emit(SIGNAL("latitudeChanged(double)"), latitude) latitude = pyqtProperty("double", latitude, setLatitude) # The longitude property is implemented with the longitude() and setlongitude() # methods, and contains the longitude of the user. def longitude(self): return self.longitudeSpinBox.value() @pyqtSignature("setLongitude(double)") def setLongitude(self, longitude): if longitude != self.longitudeSpinBox.value(): self.longitudeSpinBox.setValue(longitude) self.emit(SIGNAL("longitudeChanged(double)"), longitude) longitude = pyqtProperty("double", longitude, setLongitude) def elevation(self): return self.elevationSpinBox.value() @pyqtSignature("setElevation(double)") def setElevation(self, elevation): if elevation != self.elevationSpinBox.value(): self.elevationSpinBox.setValue(elevation) self.emit(SIGNAL("elevationChanged(double)"), elevation) elevation = pyqtProperty("double", elevation, setElevation)
class PreferencesWindow(PyDialog): """ +-------------+ | Preferences | +------------------------------+ | Text Size ______ Default | | Label Color ______ | | Label Size ______ | | Picker Size ______ | | Back Color ______ | | Text Color ______ | | | | Apply OK Cancel | +------------------------------+ """ def __init__(self, data, win_parent=None): """ Saves the data members from data and performs type checks """ PyDialog.__init__(self, data, win_parent) self._updated_preference = False self._default_font_size = data['font_size'] self._default_clipping_min = data['clipping_min'] self._default_clipping_max = data['clipping_max'] #label_color_float = data['label_color'] self._label_size = data['label_size'] #self.out_data = data self.dim_max = data['dim_max'] self._picker_size = data['picker_size'] * 100. self.label_color_float, self.label_color_int = _check_color(data['label_color']) self.background_color_float, self.background_color_int = _check_color( data['background_color']) self.text_color_float, self.text_color_int = _check_color(data['text_color']) #self.setupUi(self) self.setWindowTitle('Preferences') self.create_widgets() self.create_layout() self.set_connections() self.on_set_font(self._default_font_size) #self.show() def create_widgets(self): """creates the display window""" # Text Size self.font_size = QLabel("Text Size:") self.font_size_edit = QSpinBox(self) self.font_size_edit.setValue(self._default_font_size) self.font_size_edit.setRange(7, 20) self.font_size_button = QPushButton("Default") #----------------------------------------------------------------------- # Annotation Color self.label_color = QLabel("Label Color:") self.label_color_edit = QPushButtonColor(self.label_color_int) # Background Color self.background_color = QLabel("Background Color:") self.background_color_edit = QPushButtonColor(self.background_color_int) # Label Color self.text_color = QLabel("Text Color:") self.text_color_edit = QPushButtonColor(self.text_color_int) #----------------------------------------------------------------------- # Label Size self.label_size = QLabel("Label Size (3D Text):") self.label_size_edit = QDoubleSpinBox(self) self.label_size_edit.setRange(0.0, self.dim_max) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(6, decimals) self.label_size_edit.setDecimals(decimals) #self.label_size_edit.setSingleStep(self.dim_max / 100.) self.label_size_edit.setSingleStep(self.dim_max / 1000.) self.label_size_edit.setValue(self._label_size) #----------------------------------------------------------------------- # Picker Size self.picker_size = QLabel("Picker Size (% of Screen):") self.picker_size_edit = QDoubleSpinBox(self) self.picker_size_edit.setRange(0., 10.) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(6, decimals) self.picker_size_edit.setDecimals(decimals) self.picker_size_edit.setSingleStep(10. / 5000.) self.picker_size_edit.setValue(self._picker_size) #----------------------------------------------------------------------- # Clipping Min self.clipping_min = QLabel("Clipping Min:") self.clipping_min_edit = QLineEdit(str(self._default_clipping_min)) self.clipping_min_button = QPushButton("Default") # Clipping Max self.clipping_max = QLabel("Clipping Max:") self.clipping_max_edit = QLineEdit(str(self._default_clipping_max)) self.clipping_max_button = QPushButton("Default") #----------------------------------------------------------------------- # closing self.apply_button = QPushButton("Apply") self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Cancel") def create_layout(self): grid = QGridLayout() grid.addWidget(self.font_size, 0, 0) grid.addWidget(self.font_size_edit, 0, 1) grid.addWidget(self.font_size_button, 0, 2) grid.addWidget(self.background_color, 1, 0) grid.addWidget(self.background_color_edit, 1, 1) grid.addWidget(self.text_color, 2, 0) grid.addWidget(self.text_color_edit, 2, 1) grid.addWidget(self.label_color, 3, 0) grid.addWidget(self.label_color_edit, 3, 1) grid.addWidget(self.label_size, 4, 0) grid.addWidget(self.label_size_edit, 4, 1) grid.addWidget(self.picker_size, 5, 0) grid.addWidget(self.picker_size_edit, 5, 1) #grid.addWidget(self.clipping_min, 6, 0) #grid.addWidget(self.clipping_min_edit, 6, 1) #grid.addWidget(self.clipping_min_button, 6, 2) #grid.addWidget(self.clipping_max, 7, 0) #grid.addWidget(self.clipping_max_edit, 7, 1) #grid.addWidget(self.clipping_max_button, 7, 2) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.apply_button) ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): self.font_size_button.clicked.connect(self.on_default_font_size) self.font_size_edit.valueChanged.connect(self.on_set_font) self.label_size_edit.editingFinished.connect(self.on_label_size) self.label_size_edit.valueChanged.connect(self.on_label_size) self.label_color_edit.clicked.connect(self.on_label_color) self.background_color_edit.clicked.connect(self.on_background_color) self.text_color_edit.clicked.connect(self.on_text_color) self.picker_size_edit.valueChanged.connect(self.on_picker_size) self.picker_size_edit.editingFinished.connect(self.on_picker_size) self.picker_size_edit.valueChanged.connect(self.on_picker_size) self.clipping_min_button.clicked.connect(self.on_default_clipping_min) self.clipping_max_button.clicked.connect(self.on_default_clipping_max) self.apply_button.clicked.connect(self.on_apply) self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def on_set_font(self, value=None): """update the font for the current window""" if value is None: value = self.font_size_edit.value() font = QtGui.QFont() font.setPointSize(value) self.setFont(font) def update_label_size_color(self): if self.win_parent is not None: self.win_parent.set_labelsize_color(self._label_size, self.label_color_float) def on_label_color(self): rgb_color_ints = self.label_color_int title = "Choose a label color" passed, rgb_color_ints, rgb_color_floats = self.on_color( self.label_color_edit, rgb_color_ints, title) if passed: self.label_color_int = rgb_color_ints self.label_color_float = rgb_color_floats self.update_label_size_color() def on_background_color(self): """ Choose a background color """ rgb_color_ints = self.background_color_int title = "Choose a background color" passed, rgb_color_ints, rgb_color_floats = self.on_color( self.background_color_edit, rgb_color_ints, title) if passed: self.background_color_int = rgb_color_ints self.background_color_float = rgb_color_floats if self.win_parent is not None: self.win_parent.set_background_color(rgb_color_floats) def on_text_color(self): """ Choose a text color """ rgb_color_ints = self.text_color_int title = "Choose a text color" passed, rgb_color_ints, rgb_color_floats = self.on_color( self.text_color_edit, rgb_color_ints, title) if passed: self.text_color_int = rgb_color_ints self.text_color_float = rgb_color_floats if self.win_parent is not None: self.win_parent.set_text_color(rgb_color_floats) def on_color(self, color_edit, rgb_color_ints, title): """pops a color dialog""" col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, title) if not col.isValid(): return False, rgb_color_ints, None color_float = col.getRgbF()[:3] # floats color_int = [int(colori * 255) for colori in color_float] assert isinstance(color_float[0], float), color_float assert isinstance(color_int[0], int), color_int color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color_int) + #"border:1px solid rgb(255, 170, 255); " "}") return True, color_int, color_float def on_label_size(self): self._label_size = float(self.label_size_edit.text()) #self.on_apply(force=True) #self.min_edit.setText(str(self._default_min)) #self.min_edit.setStyleSheet("QLineEdit{background: white;}") self.update_label_size_color() def on_picker_size(self): self._picker_size = float(self.picker_size_edit.text()) if self.win_parent is not None: self.win_parent.element_picker_size = self._picker_size / 100. #self.on_apply(force=True) def on_default_font_size(self): self.font_size_edit.setValue(self._default_font_size) self.on_set_font(self._default_font_size) def on_default_clipping_min(self): self.clipping_min_edit.setText(str(self._default_clipping_min)) self.clipping_min_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_clipping_max(self): self.clipping_max_edit.setText(str(self._default_clipping_max)) self.clipping_max_edit.setStyleSheet("QLineEdit{background: white;}") @staticmethod def check_float(cell): text = cell.text() value = float(text) return value, True @staticmethod def check_label_float(cell): text = cell.text() try: value = eval_float_from_string(text) cell.setStyleSheet("QLineEdit{background: white;}") return value, True except ValueError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def on_validate(self): font_size_value, flag0 = self.check_float(self.font_size_edit) label_size_value, flag1 = self.check_float(self.label_size_edit) assert isinstance(self.label_color_float[0], float), self.label_color_float assert isinstance(self.label_color_int[0], int), self.label_color_int picker_size_value, flag2 = self.check_float(self.picker_size_edit) clipping_min_value, flag3 = self.check_label_float(self.clipping_min_edit) clipping_max_value, flag4 = self.check_label_float(self.clipping_max_edit) if all([flag0, flag1, flag2, flag3, flag4]): self._label_size = label_size_value self._picker_size = picker_size_value self.out_data['font_size'] = int(font_size_value) self.out_data['clipping_min'] = min(clipping_min_value, clipping_max_value) self.out_data['clipping_max'] = max(clipping_min_value, clipping_max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self, force=False): passed = self.on_validate() if (passed or force) and self.win_parent is not None: self.win_parent.on_set_font_size(self.out_data['font_size']) #self.win_parent.set_labelsize_color(self._label_size, self.label_color_float) #self.win_parent.element_picker_size = self._picker_size / 100. if passed and self.win_parent is not None: self.win_parent._apply_clipping(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['close'] = True self.close()
class ModifyLabelPropertiesMenu(QDialog): def __init__(self, data, win_parent=None): self.win_parent = win_parent float_color = data['color'] assert len(float_color) == 3, float_color assert isinstance(float_color[0], float), float_color self.float_color = float_color self.int_color = [int(colori * 255) for colori in float_color] assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color self._size = data['size'] self.out_data = data self.dim_max = data['dim_max'] QDialog.__init__(self, win_parent) self.setWindowTitle('Modify Label Properties') self.create_widgets() self.create_layout() self.set_connections() width = 260 height = 130 self.resize(width, height) #self.show() def create_widgets(self): # Min self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) qcolor = QtGui.QColor() qcolor.setRgb(*self.int_color) palette = QtGui.QPalette(self.color_edit.palette()) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(self.int_color) + #"border:1px solid rgb(255, 170, 255); " "}") # Size self.size = QLabel("Size:") self.size_edit = QDoubleSpinBox(self) self.size_edit.setRange(0.0, self.dim_max) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(6, decimals) self.size_edit.setDecimals(decimals) #self.size_edit.setSingleStep(self.dim_max / 100.) self.size_edit.setSingleStep(self.dim_max / 1000.) self.size_edit.setValue(self._size) # closing #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") def create_layout(self): grid = QGridLayout() grid.addWidget(self.color, 0, 0) grid.addWidget(self.color_edit, 0, 1) #grid.addWidget(self.min_button, 0, 2) grid.addWidget(self.size, 1, 0) grid.addWidget(self.size_edit, 1, 1) ok_cancel_box = QHBoxLayout() #ok_cancel_box.addWidget(self.apply_button) #ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox) self.layout() def on_color(self): rgb_color_ints = self.int_color col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a label color") if col.isValid(): float_color = col.getRgbF()[:3] # floats self.int_color = [int(colori * 255) for colori in float_color] self.float_color = float_color assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(self.int_color) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=True) #def on_color(self): #pass def set_connections(self): self.size_edit.valueChanged.connect(self.on_size) if qt_version == 4: self.connect(self.size_edit, QtCore.SIGNAL('editingFinished()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('valueChanged()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('clicked()'), self.on_size) self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.size_edit.editingFinished.connect(self.on_size) self.size_edit.valueChanged.connect(self.on_size) #self.size_edit.clicked self.color_edit.clicked.connect(self.on_color) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.out_data['close'] = True event.accept() def on_size(self): self._size = float(self.size_edit.text()) self.on_apply(force=True) #self.min_edit.setText(str(self._default_min)) #self.min_edit.setStyleSheet("QLineEdit{background: white;}") @staticmethod def check_float(cell): text = cell.text() value = float(text) return value, True #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): size_value, flag0 = self.check_float(self.size_edit) assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color if flag0: self._size = size_value #self.out_data['min'] = min(min_value, max_value) #self.out_data['max'] = max(min_value, max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self, force=False): passed = self.on_validate() if (passed or Force) and self.win_parent is not None: self.win_parent.set_labelsize_color(self._size, self.float_color) return passed def on_ok(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False self.out_data['close'] = True passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['clicked_cancel'] = True self.out_data['close'] = True self.close()
class SettingsDialog(QDialog): def __init__(self, settings, callback, parent=None): super(SettingsDialog, self).__init__(parent) # Function to apply changes self.callback = callback self.settings = settings # Dialog properties self.resize(320, 190) self.setWindowTitle('Settings') # Create, connect and add Widgets self.createWidgets() self.createConnections() self.addWidgets() def createWidgets(self): numeric_reg = QRegExp(r"[0-9]+") self.line_width_label = QLabel('Line Width') self.line_width_edit = QLineEdit() self.line_width_edit.setValidator(QRegExpValidator(numeric_reg, self)) self.line_width_edit.setText(str(self.settings['plotLineWidth'])) self.horizontal_grid_label = QLabel('Horizontal Grid') self.horizontal_grid_checkbox = QCheckBox() self.horizontal_grid_checkbox.setChecked( self.settings['horizontalGrid']) self.vertical_grid_label = QLabel('Vertical Grid') self.vertical_grid_checkbox = QCheckBox() self.vertical_grid_checkbox.setChecked(self.settings['verticalGrid']) self.grid_opacity_label = QLabel('Line Opacity') self.grid_opacity_spinbox = QDoubleSpinBox() self.grid_opacity_spinbox.setRange(0.10, 1.00) self.grid_opacity_spinbox.setSingleStep(0.10) self.grid_opacity_spinbox.setValue(float(self.settings['gridOpacity'])) self.grid_opacity_spinbox.setFocusPolicy(Qt.NoFocus) self.line_color_label = QLabel('Line Color') self.line_color_combo = QComboBox() self.line_color_combo.addItem('blue') self.line_color_combo.addItem('cyan') self.line_color_combo.addItem('green') self.line_color_combo.addItem('magenta') self.line_color_combo.addItem('white') self.line_color_combo.addItem('yellow') print self.settings['lineColor'] self.line_color_combo.setCurrentIndex( self.line_color_combo.findText(self.settings['lineColor'])) self.serial_baud_label = QLabel('Serial Baud') self.serial_baud_edit = QLineEdit() self.serial_baud_edit.setText(str(self.settings['serialBaud'])) self.serial_baud_edit.setValidator(QRegExpValidator(numeric_reg, self)) self.separator_label = QLabel('Separator') self.separator_edit = QLineEdit() self.separator_edit.setText(self.settings['separator']) self.separator_edit.setInputMask('X') self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Close | QDialogButtonBox.RestoreDefaults) # Connect elements to their events def createConnections(self): self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect( self.apply) self.buttonBox.button(QDialogButtonBox.Apply).setDefault(True) self.buttonBox.button(QDialogButtonBox.Apply).setAutoDefault(True) self.buttonBox.rejected.connect(self.reject) self.buttonBox.button( QDialogButtonBox.RestoreDefaults).clicked.connect( self.restore_defaults) self.buttonBox.button( QDialogButtonBox.RestoreDefaults).setDefault(False) self.buttonBox.button( QDialogButtonBox.RestoreDefaults).setAutoDefault(False) # Add elements to the GUI def addWidgets(self): grid = QGridLayout() grid.addWidget(self.line_width_label, 0, 0) grid.addWidget(self.line_width_edit, 0, 1) grid.addWidget(self.horizontal_grid_label, 1, 0) grid.addWidget(self.horizontal_grid_checkbox, 1, 1) grid.addWidget(self.vertical_grid_label, 2, 0) grid.addWidget(self.vertical_grid_checkbox, 2, 1) grid.addWidget(self.grid_opacity_label, 3, 0) grid.addWidget(self.grid_opacity_spinbox, 3, 1) grid.addWidget(self.line_color_label, 4, 0) grid.addWidget(self.line_color_combo, 4, 1) grid.addWidget(self.serial_baud_label, 5, 0) grid.addWidget(self.serial_baud_edit, 5, 1) grid.addWidget(self.separator_label, 6, 0) grid.addWidget(self.separator_edit, 6, 1) grid.addWidget(self.buttonBox, 7, 0, 1, 2) self.setLayout(grid) # Apply new Settings def apply(self): # dict(plotLineWidth=1, horizontalGrid=True, verticalGrid=True, gridOpacity=1, lineColor='b', # arrayPlotSize=25, updatePlotTime=1) self.settings['plotLineWidth'] = int(self.line_width_edit.text()) self.settings[ 'horizontalGrid'] = self.horizontal_grid_checkbox.isChecked() self.settings['verticalGrid'] = self.vertical_grid_checkbox.isChecked() self.settings['gridOpacity'] = float(self.grid_opacity_spinbox.value()) self.settings['lineColor'] = unicode( self.line_color_combo.currentText()) self.settings['serialBaud'] = int(self.serial_baud_edit.text()) if len(self.separator_edit.text()) != 1: self.settings['separator'] = ' ' else: self.settings['separator'] = unicode(self.separator_edit.text()) self.callback() # Restores default settings values def restore_defaults(self): default_values = dict(plotLineWidth=1, horizontalGrid=True, verticalGrid=True, gridOpacity=1, lineColor='b', arrayPlotSize=25, serialBaud=115200, separator=' ') self.settings.update(default_values) self.callback() self.line_width_edit.setText(str(self.settings['plotLineWidth'])) self.horizontal_grid_checkbox.setChecked( self.settings['horizontalGrid']) self.vertical_grid_checkbox.setChecked(self.settings['verticalGrid']) self.grid_opacity_spinbox.setValue(self.settings['gridOpacity']) self.line_color_combo.setCurrentIndex(0) self.serial_baud_edit.setText(str(self.settings['serialBaud'])) self.separator_edit.setText(self.settings['separator'])
class OffsetWidget(QWidget): """This widet displays the elements for editing the offset. This widget deals with the logic of when the new offset should be taken into account internally. When it determines that the new offset should be used, it emits the 'new_offset' signal. Parameters ---------- parent : ? Attributes ---------- offset_entry : QDoubleSpinBox The numerical element where the user can enter the offset. The units are determined by the currently displayed channel. Methods ------- toggle_preview Determine how the new_offset signal should be emitted and connect the proper element to the emit_new_offset method. emit_new_offset Wrapper function for connecting one of the widget's element's signals to the new_offset signal. Signals ------- new_offset Indicates that a new offset has been entered and is ready to be used in calculations. """ # Define a new signal called 'new_offset' new_offset = pyqtSignal() def __init__(self, parent=None): super(OffsetWidget, self).__init__(parent) # Create the numerical entry spinbox and its label offset_label = QLabel("Offset") self.offset_entry = QDoubleSpinBox(self) self.offset_entry.setDecimals(10) self.offset_entry.setRange(-1000000,1000000) # Create the preview checkbox and its label preview_chkbx_lbl = QLabel("preview") self.preview_chkbx = QCheckBox() # Create the 'Show' and 'Save' push buttons self.show_btn = QPushButton("Show") self.save_btn = QPushButton("Save") # The save feature is planned for later, so the button is disabled for # now self.save_btn.setEnabled(False) # Create the layout for the checkbox/button strip at the bottom of the # widget's layout: # | checkbox | checkbox label | show button | save button | btn_layout = QHBoxLayout() btn_layout.addWidget(self.preview_chkbx) btn_layout.addWidget(preview_chkbx_lbl) btn_layout.addWidget(self.show_btn) btn_layout.addWidget(self.save_btn) # Create the main layout of the widget: # | spinbox label | # | spinbox | # | checkbox/button layout | layout = QVBoxLayout() layout.addWidget(offset_label) layout.addWidget(self.offset_entry) layout.addLayout(btn_layout) # Set the layout self.setLayout(layout) # Connect the checkbox's 'stateChanged' signal to the toggle_preview # method self.preview_chkbx.stateChanged.connect(self.toggle_preview) # Connect the show button's 'clicked' signal to the emit_new_offset # method. # By default the checkbox is not selected, thus the default is that the # show button is how the user indicates that there is a new offset. self.show_btn.clicked.connect(self.emit_new_offset) def toggle_preview(self): """Toggle previewing offset changes automatically. This function checks the state of the preview checkbox and establishes the Offset_Widget's method of emitting the new_offset signal. """ # Connect and disconnect the spinbox's and show button's signals to the # widget's new_offset signal. if self.preview_chkbx.isChecked(): # Preview is selected: # show button is disconnected from new_offset # spinbox is connected to new_offset self.show_btn.clicked.disconnect(self.emit_new_offset) self.offset_entry.editingFinished.connect(self.emit_new_offset) elif not self.preview_chkbx.isChecked(): # Preview is not selected: # spinbox is disconnected from new_offset # show button is connected to new_offset self.offset_entry.editingFinished.disconnect(self.emit_new_offset) self.show_btn.clicked.connect(self.emit_new_offset) # Enable or disable the show button depending on checkbox's state self.show_btn.setEnabled(not self.preview_chkbx.isChecked()) def emit_new_offset(self): """Emit the 'new_offset' signal. The function just provides an easy way to connect other signals to emitting the widget's new_offset signal. """ self.new_offset.emit()
class Img2GifWidget(QDialog): AppName = u"GIF生成工具" def __init__(self, parent=None): super(Img2GifWidget, self).__init__(parent) self.setWindowTitle(Img2GifWidget.AppName) self.listWidget = QListWidget() self.listWidget.setMinimumSize(400, 300) self.btnAdd = QPushButton("&Add") self.btnUp = QPushButton("&Up") self.btnDown = QPushButton("&Down") self.btnDel = QPushButton("&Delete") self.btnClear = QPushButton("&Clear") topLeftLay = QVBoxLayout() topLeftLay.addWidget(self.btnAdd) topLeftLay.addWidget(self.btnUp) topLeftLay.addWidget(self.btnDown) topLeftLay.addWidget(self.btnDel) topLeftLay.addWidget(self.btnClear) topLeftLay.addStretch() topLay = QHBoxLayout() topLay.addWidget(self.listWidget) topLay.addLayout(topLeftLay) label = QLabel(u"Gif文件路径:") self.txtGifPath = QLineEdit() self.btnBrowser = QPushButton('...') midLay = QHBoxLayout() midLay.addWidget(label) midLay.addWidget(self.txtGifPath) midLay.addWidget(self.btnBrowser) timeLabel = QLabel(u"时间间隔:") self.spbTime = QDoubleSpinBox() self.spbTime.setRange(0.001, 10) self.spbTime.setSingleStep(0.001) self.spbTime.setValue(1) self.spbTime.setSuffix('s') loopLabel = QLabel(u"循环:") self.spbLoop = QDoubleSpinBox() self.spbLoop = QSpinBox() self.spbLoop.setRange(0, 1000) self.spbLoop.setSingleStep(1) self.spbLoop.setValue(0) self.spbLoop.setToolTip(u"0次循环表示永久循环") self.spbLoop.setSuffix(u"次") self.btnBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bottomLay = QHBoxLayout() bottomLay.addWidget(timeLabel) bottomLay.addWidget(self.spbTime) bottomLay.addWidget(loopLabel) bottomLay.addWidget(self.spbLoop) bottomLay.addStretch() bottomLay.addWidget(self.btnBox) mainLay = QVBoxLayout() mainLay.addLayout(topLay) mainLay.addLayout(midLay) mainLay.addLayout(bottomLay) self.setLayout(mainLay) self.btnAdd.clicked.connect(self.itemAdd) self.btnUp.clicked.connect(self.itemUp) self.btnDown.clicked.connect(self.itemDown) self.btnDel.clicked.connect(self.itemDel) self.btnClear.clicked.connect(self.listWidget.clear) self.btnBrowser.clicked.connect(self.setGifPath) self.btnBox.rejected.connect(self.close) self.btnBox.accepted.connect(self.makeGif) self.txtGifPath.returnPressed.connect(self.updateGifPath) def itemAdd(self): fileNames = QFileDialog.getOpenFileNames(None, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName), '.', u'所有文件(*.*);;BMP文件(*.bmp);;PNG文件(*.png);;JPG文件(*.jpg *.jpeg)') for fn in fileNames: f = QFileInfo(fn) if unicode(f.suffix().toLower()) in ['jpg', 'png', 'bmp', 'jpeg']: self.listWidget.addItem(fn) def itemUp(self): row = self.listWidget.currentRow() if row <= 0: return item = self.listWidget.currentItem() self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentRow(row - 1) def itemDown(self): rows = self.listWidget.count() row = self.listWidget.currentRow() if (row < 0) or (row == rows - 1): return item = self.listWidget.currentItem() self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentRow(row + 1) def itemDel(self): row = self.listWidget.currentRow() if row >= 0: self.listWidget.takeItem(row) def setGifPath(self): filename = QFileDialog.getSaveFileName(self, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName), ".", "Gif(*.gif)") self.txtGifPath.setText(filename) def updateGifPath(self): fileName = self.txtGifPath.text() f = QFileInfo(fileName) if f.dir().exists and not f.baseName().isEmpty() and not f.suffix().isEmpty(): self.txtGifPath.setText(fileName) return True else: QMessageBox.warning(self, u"{0} -- warning".format(Img2GifWidget.AppName), u"要生成的GIF存储路径{0}不是有效的GIF文件".format(unicode(fileName))) return False def makeGif(self): imgs = [unicode(self.listWidget.item(i).text()) for i in range(self.listWidget.count())] if len(imgs) <= 1: QMessageBox.warning(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"GIF动画文件必须要给定大于一张图片。") return if not self.updateGifPath(): return durations = self.spbTime.value() loops = self.spbLoop.value() ok, msg = img2gif.images2gif(imgs, self.txtGifPath.text(), durations=durations, loops=loops) if ok: QMessageBox.about(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"Succeed!\n{0}".format(msg)) qApp.processEvents() else: QMessageBox.about(u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"sorry! Failed to generate the {0}".format(unicode(self.txtGifPath)))
class EditGeometryProperties(QDialog): force = True allow_update = True def __init__(self, data, win_parent=None): """ +------------------+ | Edit Actor Props | +------------------+------+ | Name1 | | Name2 | | Name3 | | Name4 | | | | Active_Name main | | Color box | | Line_Width 2 | | Point_Size 2 | | Bar_Scale 2 | | Opacity 0.5 | | Show/Hide | | | | Apply OK Cancel | +-------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Geometry Properties') #default self.win_parent = win_parent self.out_data = data self.keys = sorted(data.keys()) self.keys = data.keys() keys = self.keys nrows = len(keys) self.active_key = 'main'#keys[0] items = keys header_labels = ['Groups'] table_model = Model(items, header_labels, self) view = CustomQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version == 4: view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table = view actor_obj = data[self.active_key] name = actor_obj.name line_width = actor_obj.line_width point_size = actor_obj.point_size bar_scale = actor_obj.bar_scale opacity = actor_obj.opacity color = actor_obj.color show = actor_obj.is_visible self.representation = actor_obj.representation # table header = self.table.horizontalHeader() header.setStretchLastSection(True) self._default_is_apply = False self.name = QLabel("Name:") self.name_edit = QLineEdit(str(name)) self.name_edit.setDisabled(True) self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data[self.active_key].color qcolor = QtGui.QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QtGui.QPalette(self.color_edit.palette()) # make a copy of the palette #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \ #qcolor) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.use_slider = True self.is_opacity_edit_active = False self.is_opacity_edit_slider_active = False self.is_line_width_edit_active = False self.is_line_width_edit_slider_active = False self.is_point_size_edit_active = False self.is_point_size_edit_slider_active = False self.is_bar_scale_edit_active = False self.is_bar_scale_edit_slider_active = False self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) if self.use_slider: self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal) self.opacity_slider_edit.setRange(1, 10) self.opacity_slider_edit.setValue(opacity * 10) self.opacity_slider_edit.setTickInterval(1) self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow) self.line_width = QLabel("Line Width:") self.line_width_edit = QSpinBox(self) self.line_width_edit.setRange(1, 15) self.line_width_edit.setSingleStep(1) self.line_width_edit.setValue(line_width) if self.use_slider: self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal) self.line_width_slider_edit.setRange(1, 15) self.line_width_slider_edit.setValue(line_width) self.line_width_slider_edit.setTickInterval(1) self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation in ['point', 'surface']: self.line_width.setEnabled(False) self.line_width_edit.setEnabled(False) self.line_width_slider_edit.setEnabled(False) self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 15) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) if self.use_slider: self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal) self.point_size_slider_edit.setRange(1, 15) self.point_size_slider_edit.setValue(point_size) self.point_size_slider_edit.setTickInterval(1) self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow) self.point_size_slider_edit.setVisible(False) if self.representation in ['wire', 'surface']: self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.bar_scale = QLabel("Bar Scale:") self.bar_scale_edit = QDoubleSpinBox(self) #self.bar_scale_edit.setRange(0.01, 1.0) # was 0.1 #self.bar_scale_edit.setRange(0.05, 5.0) self.bar_scale_edit.setDecimals(1) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) self.bar_scale_edit.setSingleStep(0.1) self.bar_scale_edit.setValue(bar_scale) #if self.use_slider: #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal) #self.bar_scale_slider_edit.setRange(1, 100) # 1/0.05 = 100/5.0 #self.bar_scale_slider_edit.setValue(opacity * 0.05) #self.bar_scale_slider_edit.setTickInterval(10) #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation != 'bar': self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setEnabled(False) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) # closing # self.apply_button = QPushButton("Apply") #if self._default_is_apply: #self.apply_button.setDisabled(True) # self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") self.create_layout() self.set_connections() def on_update_geometry_properties_window(self, data): """Not Implemented""" return new_keys = sorted(data.keys()) if self.active_key in new_keys: i = new_keys.index(self.active_key) else: i = 0 self.table.update_data(new_keys) self.out_data = data self.update_active_key(i) def update_active_key(self, index): """ Parameters ---------- index : PyQt4.QtCore.QModelIndex the index of the list Internal Parameters ------------------- name : str the name of obj obj : CoordProperties, AltGeometry the storage object for things like line_width, point_size, etc. """ old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() if qt_version == 4: name = str(index.data().toString()) else: name = str(index.data()) print('name = %r' % name) #i = self.keys.index(self.active_key) self.active_key = name self.name_edit.setText(name) obj = self.out_data[name] if isinstance(obj, CoordProperties): opacity = 1.0 representation = 'coord' is_visible = obj.is_visible elif isinstance(obj, AltGeometry): line_width = obj.line_width point_size = obj.point_size bar_scale = obj.bar_scale opacity = obj.opacity representation = obj.representation is_visible = obj.is_visible self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.allow_update = False self.force = False self.line_width_edit.setValue(line_width) self.point_size_edit.setValue(point_size) self.bar_scale_edit.setValue(bar_scale) self.force = True self.allow_update = True else: raise NotImplementedError(obj) allowed_representations = [ 'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar'] if self.representation != representation: self.representation = representation if representation not in allowed_representations: msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % ( name, representation, allowed_representations) if self.representation == 'coord': self.color.setVisible(False) self.color_edit.setVisible(False) self.line_width.setVisible(False) self.line_width_edit.setVisible(False) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) self.opacity.setVisible(False) self.opacity_edit.setVisible(False) if self.use_slider: self.opacity_slider_edit.setVisible(False) self.point_size_slider_edit.setVisible(False) self.line_width_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setVisible(True) self.color_edit.setVisible(True) self.line_width.setVisible(True) self.line_width_edit.setVisible(True) self.point_size.setVisible(True) self.point_size_edit.setVisible(True) self.bar_scale.setVisible(True) #self.bar_scale_edit.setVisible(True) self.opacity.setVisible(True) self.opacity_edit.setVisible(True) if self.use_slider: self.opacity_slider_edit.setVisible(True) self.line_width_slider_edit.setVisible(True) self.point_size_slider_edit.setVisible(True) #self.bar_scale_slider_edit.setVisible(True) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) self.line_width.setEnabled(True) self.line_width_edit.setEnabled(True) self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) show_points = False show_line_width = True show_bar_scale = False if self.use_slider: self.line_width_slider_edit.setEnabled(True) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setEnabled(True) self.color_edit.setEnabled(True) show_points = False if self.representation in ['point', 'wire+point']: show_points = True show_line_width = False if self.representation in ['wire', 'wire+point', 'bar']: show_line_width = True if representation == 'bar': show_bar_scale = True else: show_bar_scale = False #self.bar_scale_button.setVisible(show_bar_scale) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) #if self.use_slider: #self.bar_scale_slider_edit.setEnabled(False) self.point_size.setEnabled(show_points) self.point_size_edit.setEnabled(show_points) self.point_size.setVisible(show_points) self.point_size_edit.setVisible(show_points) self.line_width.setEnabled(show_line_width) self.line_width_edit.setEnabled(show_line_width) self.bar_scale.setEnabled(show_bar_scale) self.bar_scale_edit.setEnabled(show_bar_scale) self.bar_scale.setVisible(show_bar_scale) self.bar_scale_edit.setVisible(show_bar_scale) if self.use_slider: self.point_size_slider_edit.setEnabled(show_points) self.point_size_slider_edit.setVisible(show_points) self.line_width_slider_edit.setEnabled(show_line_width) #if self.representation in ['wire', 'surface']: self.opacity_edit.setValue(opacity) #if self.use_slider: #self.opacity_slider_edit.setValue(opacity*10) self.checkbox_show.setChecked(is_visible) self.checkbox_hide.setChecked(not is_visible) passed = self.on_validate() #self.on_apply(force=True) # TODO: was turned on...do I want this??? #self.allow_update = True #def on_name_select(self): #print('on_name_select') #return def create_layout(self): ok_cancel_box = QHBoxLayout() # ok_cancel_box.addWidget(self.apply_button) # ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) grid = QGridLayout() irow = 0 grid.addWidget(self.name, irow, 0) grid.addWidget(self.name_edit, irow, 1) irow += 1 grid.addWidget(self.color, irow, 0) grid.addWidget(self.color_edit, irow, 1) irow += 1 grid.addWidget(self.opacity, irow, 0) if self.use_slider: grid.addWidget(self.opacity_edit, irow, 2) grid.addWidget(self.opacity_slider_edit, irow, 1) else: grid.addWidget(self.opacity_edit, irow, 1) irow += 1 grid.addWidget(self.line_width, irow, 0) if self.use_slider: grid.addWidget(self.line_width_edit, irow, 2) grid.addWidget(self.line_width_slider_edit, irow, 1) else: grid.addWidget(self.line_width_edit, irow, 1) irow += 1 grid.addWidget(self.point_size, irow, 0) if self.use_slider: grid.addWidget(self.point_size_edit, irow, 2) grid.addWidget(self.point_size_slider_edit, irow, 1) else: grid.addWidget(self.point_size_edit, irow, 1) irow += 1 grid.addWidget(self.bar_scale, irow, 0) if self.use_slider and 0: grid.addWidget(self.bar_scale_edit, irow, 2) grid.addWidget(self.bar_scale_slider_edit, irow, 1) else: grid.addWidget(self.bar_scale_edit, irow, 1) irow += 1 checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(grid) if 0: vbox.addWidget(self.checkbox_show) vbox.addWidget(self.checkbox_hide) else: vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) vbox.addLayout(vbox1) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): # self.opacity_edit.connect(arg0, QObject, arg1) if qt_version == 4: self.connect(self.opacity_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #self.connect(self.opacity_slider_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #grid.addWidget(self.opacity_slider_edit, irow, 1) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_point_size) self.connect(self.line_width_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) self.connect(self.point_size_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) self.connect(self.bar_scale_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_bar_scale) else: self.opacity_edit.valueChanged.connect(self.on_opacity) self.line_width_edit.valueChanged.connect(self.on_line_width) self.point_size_edit.valueChanged.connect(self.on_point_size) self.bar_scale_edit.valueChanged.connect(self.on_bar_scale) if self.use_slider: self.opacity_slider_edit.valueChanged.connect(self.on_opacity_slider) self.line_width_slider_edit.valueChanged.connect(self.on_line_width_slider) self.point_size_slider_edit.valueChanged.connect(self.on_point_size_slider) #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider) # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) if qt_version == 4: self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show) self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide) #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply) # self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) # self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.color_edit.clicked.connect(self.on_color) self.checkbox_show.clicked.connect(self.on_show) self.checkbox_hide.clicked.connect(self.on_hide) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.on_cancel() def on_color(self): name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QtGui.QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color = col.getRgbF()[:3] obj.color = color #print('new_color =', color) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) def on_show(self): name = self.active_key is_checked = self.checkbox_show.isChecked() self.out_data[name].is_visible = is_checked self.on_apply(force=self.force) def on_hide(self): name = self.active_key is_checked = self.checkbox_hide.isChecked() self.out_data[name].is_visible = not is_checked self.on_apply(force=self.force) def on_line_width(self): self.is_line_width_edit_active = True name = self.active_key line_width = self.line_width_edit.value() self.out_data[name].line_width = line_width if not self.is_line_width_edit_slider_active: if self.use_slider: self.line_width_slider_edit.setValue(line_width) self.is_line_width_edit_active = False self.on_apply(force=self.force) self.is_line_width_edit_active = False def on_line_width_slider(self): self.is_line_width_edit_slider_active = True name = self.active_key line_width = self.line_width_slider_edit.value() if not self.is_line_width_edit_active: self.line_width_edit.setValue(line_width) self.is_line_width_edit_slider_active = False def on_point_size(self): self.is_point_size_edit_active = True name = self.active_key point_size = self.point_size_edit.value() self.out_data[name].point_size = point_size if not self.is_point_size_edit_slider_active: if self.use_slider: self.point_size_slider_edit.setValue(point_size) self.is_point_size_edit_active = False self.on_apply(force=self.force) self.is_point_size_edit_active = False def on_point_size_slider(self): self.is_point_size_edit_slider_active = True name = self.active_key point_size = self.point_size_slider_edit.value() if not self.is_point_size_edit_active: self.point_size_edit.setValue(point_size) self.is_point_size_edit_slider_active = False def on_bar_scale(self): self.is_bar_scale_edit_active = True name = self.active_key float_bar_scale = self.bar_scale_edit.value() self.out_data[name].bar_scale = float_bar_scale if not self.is_bar_scale_edit_slider_active: int_bar_scale = int(round(float_bar_scale * 20, 0)) #if self.use_slider: #self.bar_scale_slider_edit.setValue(int_bar_scale) self.is_bar_scale_edit_active = False self.on_apply(force=self.force) self.is_bar_scale_edit_active = False def on_bar_scale_slider(self): self.is_bar_scale_edit_slider_active = True name = self.active_key int_bar_scale = self.bar_scale_slider_edit.value() if not self.is_bar_scale_edit_active: float_bar_scale = int_bar_scale / 20. self.bar_scale_edit.setValue(float_bar_scale) self.is_bar_scale_edit_slider_active = False def on_opacity(self): self.is_opacity_edit_active = True name = self.active_key float_opacity = self.opacity_edit.value() self.out_data[name].opacity = float_opacity if not self.is_opacity_edit_slider_active: int_opacity = int(round(float_opacity * 10, 0)) if self.use_slider: self.opacity_slider_edit.setValue(int_opacity) self.is_opacity_edit_active = False self.on_apply(force=self.force) self.is_opacity_edit_active = False def on_opacity_slider(self): self.is_opacity_edit_slider_active = True name = self.active_key int_opacity = self.opacity_slider_edit.value() if not self.is_opacity_edit_active: float_opacity = int_opacity / 10. self.opacity_edit.setValue(float_opacity) self.is_opacity_edit_slider_active = False #def on_axis(self, text): ##print(self.combo_axis.itemText()) #self._axis = str(text) #self.plane.setText('Point on %s? Plane:' % self._axis) #self.point_a.setText('Point on %s Axis:' % self._axis) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def on_plane(self, text): #self._plane = str(text) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) def on_check_apply(self): is_checked = self.check_apply.isChecked() self.apply_button.setDisabled(is_checked) def _on_float(self, field): try: eval_float_from_string(field.text()) field.setStyleSheet("QLineEdit{background: white;}") except ValueError: field.setStyleSheet("QLineEdit{background: red;}") #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self, force=False): passed = self.on_validate() if (passed or force) and self.allow_update: self.win_parent.on_update_geometry_properties(self.out_data) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
class Widget(QWidget): # I think we will work with individual editor objects for different types of objects. # Each one will be shown/hidden on demand, i.e. when an element is activated # through the SVG view, the music view or the cursor in the source. # Each editor object handles its own connections to signals. # (PS: The object editor will also work with the source code directly, # i.e. independently of graphical SVG editing.) def __init__(self, tool): super(Widget, self).__init__(tool) self.mainwindow = tool.mainwindow() self.define = None import panelmanager self.svgview = panelmanager.manager( tool.mainwindow()).svgview.widget().view layout = QVBoxLayout(spacing=1) self.setLayout(layout) self.elemLabel = QLabel() self.XOffsetBox = QDoubleSpinBox() self.XOffsetBox.setRange(-99, 99) self.XOffsetBox.setSingleStep(0.1) self.XOffsetLabel = l = QLabel() l.setBuddy(self.XOffsetBox) self.YOffsetBox = QDoubleSpinBox() self.YOffsetBox.setRange(-99, 99) self.YOffsetBox.setSingleStep(0.1) self.YOffsetLabel = l = QLabel() l.setBuddy(self.YOffsetBox) self.insertButton = QPushButton("insert offset in source", self) self.insertButton.clicked.connect(self.callInsert) layout.addWidget(self.elemLabel) layout.addWidget(self.XOffsetLabel) layout.addWidget(self.XOffsetBox) layout.addWidget(self.YOffsetLabel) layout.addWidget(self.YOffsetBox) layout.addWidget(self.insertButton) layout.addStretch(1) app.translateUI(self) self.loadSettings() self.connectSlots() def connectSlots(self): # On creation we connect to all available signals self.connectToSvgView() def connectToSvgView(self): """Register with signals emitted by the SVG viewer for processing graphical editing. """ self.svgview.objectStartDragging.connect(self.startDragging) self.svgview.objectDragging.connect(self.Dragging) self.svgview.objectDragged.connect(self.Dragged) self.svgview.cursor.connect(self.setObjectFromCursor) def disconnectFromSvgView(self): """Do not process graphical edits when the Object Editor isn't visible.""" self.svgview.objectStartDragging.disconnect() self.svgview.objectDragging.disconnect() self.svgview.objectDragged.disconnect() self.svgview.cursor.disconnect() def translateUI(self): self.XOffsetLabel.setText(_("X Offset")) self.XOffsetBox.setToolTip(_("Display the X Offset")) self.YOffsetLabel.setText(_("Y Offset")) self.YOffsetBox.setToolTip(_("Display the Y Offset")) self.insertButton.setEnabled(False) def hideEvent(self, event): """Disconnect from all graphical editing signals when the panel isn't visible """ self.disconnectFromSvgView() event.accept() def showEvent(self, event): """Connect to the graphical editing signals when the panel becomes visible """ self.connectToSvgView() event.accept() def callInsert(self): """ Insert the override command in the source.""" if self.define: self.define.insertOverride(self.XOffsetBox.value(), self.YOffsetBox.value()) @QtCore.pyqtSlot(float, float) def setOffset(self, x, y): """Display the updated offset.""" self.XOffsetBox.setValue(x) self.YOffsetBox.setValue(y) @QtCore.pyqtSlot(float, float) def startDragging(self, x, y): """Set the value of the offset externally.""" # temporary debug output #print("Start dragging with offset", x, y) self.setOffset(x, y) @QtCore.pyqtSlot(float, float) def Dragging(self, x, y): """Set the value of the offset externally.""" # temporary debug output # print("Dragging with offset", x, y) self.setOffset(x, y) @QtCore.pyqtSlot(float, float) def Dragged(self, x, y): """Set the value of the offset externally.""" # temporary debug output #print("Dragged to", x, y) self.setOffset(x, y) @QtCore.pyqtSlot(QTextCursor) def setObjectFromCursor(self, cursor): """Set selected element.""" self.define = defineoffset.DefineOffset( self.mainwindow.currentDocument()) self.elemLabel.setText(self.define.getCurrentLilyObject(cursor)) self.insertButton.setEnabled(True) def loadSettings(self): """Called on construction. Load settings and set checkboxes state.""" s = QSettings() s.beginGroup('object_editor') def saveSettings(self): """Called on close. Save settings and checkboxes state.""" s = QSettings() s.beginGroup('object_editor')
class FontsColors(preferences.Page): def __init__(self, dialog): super(FontsColors, self).__init__(dialog) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.scheme = SchemeSelector(self) layout.addWidget(self.scheme) self.printScheme = QCheckBox() layout.addWidget(self.printScheme) hbox = QHBoxLayout() self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) self.tree.setAnimated(True) self.stack = QStackedWidget(self) hbox.addWidget(self.tree) hbox.addWidget(self.stack) layout.addLayout(hbox) hbox = QHBoxLayout() self.fontLabel = QLabel() self.fontChooser = QFontComboBox() self.fontSize = QDoubleSpinBox() self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) hbox.addWidget(self.fontLabel) hbox.addWidget(self.fontChooser, 1) hbox.addWidget(self.fontSize) layout.addLayout(hbox) # add the items to our list self.baseColorsItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStylesItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStyles = {} for name in textformats.defaultStyles: self.defaultStyles[name] = i = QTreeWidgetItem() self.defaultStylesItem.addChild(i) i.name = name self.defaultStylesItem.setExpanded(True) self.allStyles = {} for group, styles in ly.colorize.default_mapping(): i = QTreeWidgetItem() children = {} self.allStyles[group] = (i, children) self.tree.addTopLevelItem(i) i.group = group for name, base, clss in styles: j = QTreeWidgetItem() j.name = name j.base = base i.addChild(j) children[name] = j self.baseColorsWidget = BaseColors(self) self.customAttributesWidget = CustomAttributes(self) self.emptyWidget = QWidget(self) self.stack.addWidget(self.baseColorsWidget) self.stack.addWidget(self.customAttributesWidget) self.stack.addWidget(self.emptyWidget) self.tree.currentItemChanged.connect(self.currentItemChanged) self.tree.setCurrentItem(self.baseColorsItem) self.scheme.currentChanged.connect(self.currentSchemeChanged) self.scheme.changed.connect(self.changed) self.baseColorsWidget.changed.connect(self.baseColorsChanged) self.customAttributesWidget.changed.connect(self.customAttributesChanged) self.fontChooser.currentFontChanged.connect(self.fontChanged) self.fontSize.valueChanged.connect(self.fontChanged) self.printScheme.clicked.connect(self.printSchemeChanged) app.translateUI(self) def translateUI(self): self.printScheme.setText(_("Use this scheme for printing")) self.fontLabel.setText(_("Font:")) self.baseColorsItem.setText(0, _("Base Colors")) self.defaultStylesItem.setText(0, _("Default Styles")) self.defaultStyleNames = defaultStyleNames() self.allStyleNames = allStyleNames() for name in textformats.defaultStyles: self.defaultStyles[name].setText(0, self.defaultStyleNames[name]) for group, styles in ly.colorize.default_mapping(): self.allStyles[group][0].setText(0, self.allStyleNames[group][0]) for name, base, clss in styles: self.allStyles[group][1][name].setText(0, self.allStyleNames[group][1][name]) def currentItemChanged(self, item, previous): if item is self.baseColorsItem: self.stack.setCurrentWidget(self.baseColorsWidget) elif not item.parent(): self.stack.setCurrentWidget(self.emptyWidget) else: data = self.data[self.scheme.currentScheme()] w = self.customAttributesWidget self.stack.setCurrentWidget(w) toptext = None if item.parent() is self.defaultStylesItem: # default style w.setTitle(item.text(0)) w.setTristate(False) w.setTextFormat(data.defaultStyles[item.name]) else: # specific style of specific group group, name = item.parent().group, item.name w.setTitle("{0}: {1}".format(item.parent().text(0), item.text(0))) inherit = item.base if inherit: toptext = _("(Inherits: {name})").format(name=self.defaultStyleNames[inherit]) w.setTristate(bool(inherit)) w.setTextFormat(data.allStyles[group][name]) w.setTopText(toptext) def currentSchemeChanged(self): scheme = self.scheme.currentScheme() if scheme not in self.data: self.data[scheme] = textformats.TextFormatData(scheme) self.updateDisplay() if self.tree.currentItem(): self.currentItemChanged(self.tree.currentItem(), None) with qutil.signalsBlocked(self.printScheme): self.printScheme.setChecked(scheme == self._printScheme) def fontChanged(self): data = self.data[self.scheme.currentScheme()] data.font = self.fontChooser.currentFont() data.font.setPointSizeF(self.fontSize.value()) self.updateDisplay() self.changed.emit() def printSchemeChanged(self): if self.printScheme.isChecked(): self._printScheme = self.scheme.currentScheme() else: self._printScheme = None self.changed.emit() def addSchemeData(self, scheme, tfd): self.data[scheme] = tfd def currentSchemeData(self): return self.data[self.scheme.currentScheme()] def updateDisplay(self): data = self.data[self.scheme.currentScheme()] with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(data.font) self.fontSize.setValue(data.font.pointSizeF()) with qutil.signalsBlocked(self): # update base colors for name in textformats.baseColors: self.baseColorsWidget.color[name].setColor(data.baseColors[name]) # update base colors for whole treewidget p = QApplication.palette() p.setColor(QPalette.Base, data.baseColors['background']) p.setColor(QPalette.Text, data.baseColors['text']) p.setColor(QPalette.Highlight, data.baseColors['selectionbackground']) p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext']) self.tree.setPalette(p) def setItemTextFormat(item, f): font = QFont(data.font) if f.hasProperty(QTextFormat.ForegroundBrush): item.setForeground(0, f.foreground().color()) else: item.setForeground(0, data.baseColors['text']) if f.hasProperty(QTextFormat.BackgroundBrush): item.setBackground(0, f.background().color()) else: item.setBackground(0, QBrush()) font.setWeight(f.fontWeight()) font.setItalic(f.fontItalic()) font.setUnderline(f.fontUnderline()) item.setFont(0, font) # update looks of default styles for name in textformats.defaultStyles: setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name]) # update looks of all the specific styles for group, styles in ly.colorize.default_mapping(): children = self.allStyles[group][1] for name, inherit, clss in styles: f = QTextCharFormat(data.defaultStyles[inherit]) if inherit else QTextCharFormat() f.merge(data.allStyles[group][name]) setItemTextFormat(children[name], f) def baseColorsChanged(self, name): # keep data up to date with base colors data = self.data[self.scheme.currentScheme()] data.baseColors[name] = self.baseColorsWidget.color[name].color() self.updateDisplay() self.changed.emit() def customAttributesChanged(self): item = self.tree.currentItem() if not item or not item.parent(): return data = self.data[self.scheme.currentScheme()] if item.parent() is self.defaultStylesItem: # a default style has been changed data.defaultStyles[item.name] = self.customAttributesWidget.textFormat() else: # a specific style has been changed group, name = item.parent().group, item.name data.allStyles[group][name] = self.customAttributesWidget.textFormat() self.updateDisplay() self.changed.emit() def import_(self, filename): from . import import_export import_export.importTheme(filename, self, self.scheme) def export(self, name, filename): from . import import_export try: import_export.exportTheme(self, name, filename) except (IOError, OSError) as e: QMessageBox.critical(self, _("Error"), _( "Can't write to destination:\n\n{url}\n\n{error}").format( url=filename, error=e.strerror)) def loadSettings(self): self.data = {} # holds all data with scheme as key self._printScheme = QSettings().value("printer_scheme", "default", type("")) self.scheme.loadSettings("editor_scheme", "editor_schemes") def saveSettings(self): self.scheme.saveSettings("editor_scheme", "editor_schemes", "fontscolors") for scheme in self.scheme.schemes(): if scheme in self.data: self.data[scheme].save(scheme) if self._printScheme: QSettings().setValue("printer_scheme", self._printScheme) else: QSettings().remove("printer_scheme")
class EditNodeProperties(QDialog): def __init__(self, data, win_parent=None): """ +-----------------+ | Edit Node Props | +-----------------+------+ | LEwingTip | | Node2 | | Node3 | | Node4 | | | | All Nodes: | | Color red | | PointSize 3 | | Opacity 0.3 | | Show/Hide | | | | Name LEwingTip | | Location X Y Z | | Coord 0 | | CoordType R, C, S | | | | Previous Next | | | | Close | +------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Node Properties') #default self.win_parent = win_parent self.out_data = data point_properties = data['point_properties'] print(point_properties) #name = point_properties.name point_size = point_properties.point_size opacity = point_properties.opacity color = point_properties.color show = point_properties.is_visible self.points = data['points'] self.keys = sorted(self.points.keys()) keys = self.keys #nrows = len(keys) active_point = data['active_point'] #self.active_key = keys[0] self.active_key = active_point name = self.active_key description = self.points[self.active_key][0] self._use_old_table = False items = ['Node %i' % val for val in keys] header_labels = ['Nodes'] table_model = Model(items, header_labels, self) view = SingleChoiceQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version in [4, 'pyside']: view.horizontalHeader().setResizeMode(QHeaderView.Stretch) else: view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table = view #self.representation = actor_obj.representation #print('rep =', self.representation) table = self.table #headers = [QtCore.QString('Groups')] header = table.horizontalHeader() header.setStretchLastSection(True) #---------------------------------------------- #self._default_is_apply = False self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data['point_properties'].color opacity = self.out_data['point_properties'].opacity show = self.out_data['point_properties'].is_visible #color = self.out_data[self.active_key].color qcolor = QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QPalette.Active, QPalette.Base, \ #qcolor) palette.setColor(QPalette.Background, QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.all_nodes_header = QLabel("All Nodes:") self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 10) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) #---------------------------------------------- self.nodes_header = QLabel("Single Node:") self.name = QLabel("ID:") self.name_edit = QLineEdit('Node %i' % name) self.name_edit.setDisabled(True) self.description = QLabel("Description:") self.description_edit = QLineEdit(str(description)) #self.description_edit.setDisabled(True) location_x = 0.1 location_y = 0.1 location_z = 0.1 self.location = QLabel("Location:") self.location_x_edit = QDoubleSpinBox(self) self.location_y_edit = QDoubleSpinBox(self) self.location_z_edit = QDoubleSpinBox(self) #self.location_x_edit.setDecimals(1) delta_x = abs(location_x) / 100. if location_x != 0.0 else 0.1 delta_y = abs(location_y) / 100. if location_y != 0.0 else 0.1 delta_z = abs(location_z) / 100. if location_z != 0.0 else 0.1 self.location_x_edit.setSingleStep(delta_x) self.location_y_edit.setSingleStep(delta_y) self.location_z_edit.setSingleStep(delta_z) self.location_x_edit.setValue(location_x) self.location_y_edit.setValue(location_y) self.location_z_edit.setValue(location_z) self.coord = QLabel("Coord:") self.coord_edit = QSpinBox(self) self.coord_edit.setRange(0, 99999999) #self.coord_edit.setSingleStep(1) self.coord_edit.setValue(0) self.coord_type = QLabel("Coord Type:") #---------------------------------------------- # closing #if self._default_is_apply: #self.apply_button.setDisabled(True) self.close_button = QPushButton("Close") self.create_layout() self.set_connections() def update_active_key(self, index): name = self.active_key old_obj = self.out_data['points'][name] #self.active_key #self.points[self.active_key] old_obj[0] = str(self.description_edit.text()) #old_obj.coord = self.description_edit.value() #old_obj.description = self.description_edit.value() #old_obj.description = self.description_edit.value() str_name = str(index.data().toString()) name = int(str_name[5:]) #i = self.keys.index(self.active_key) self.active_key = name point = self.points[self.active_key] #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], self.name_edit.setText(str(self.active_key)) self.description_edit.setText(point[0]) self.coord_edit.setValue(point[1]) if point[2] == 'R': self.radio_rectangular.setChecked(True) elif point[2] == 'C': self.radio_cylindrical.setChecked(True) elif point[2] == 'S': self.radio_spherical.setChecked(True) self.location_x_edit.setValue(point[3]) self.location_y_edit.setValue(point[4]) self.location_z_edit.setValue(point[5]) #obj = self.out_data[name] #point_size = obj.point_size #opacity = obj.opacity #representation = obj.representation #is_visible = obj.is_visible #self.opacity_edit.setValue(opacity) #self.checkbox_show.setChecked(is_visible) #self.checkbox_hide.setChecked(not is_visible) #def on_name_select(self): #print('on_name_select') #return def create_layout(self): cancel_box = QHBoxLayout() cancel_box.addWidget(self.close_button) grid1 = QGridLayout() grid2 = QGridLayout() #----------------------------------------- # setup self.radio_rectangular = QRadioButton('Rectangular') self.radio_cylindrical = QRadioButton('Cylindrical') self.radio_spherical = QRadioButton('Spherical') coord_type_layout = QHBoxLayout() coord_type_layout.addWidget(self.radio_rectangular) coord_type_layout.addWidget(self.radio_cylindrical) coord_type_layout.addWidget(self.radio_spherical) location_layout = QHBoxLayout() location_layout.addWidget(self.location_x_edit) location_layout.addWidget(self.location_y_edit) location_layout.addWidget(self.location_z_edit) checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) #vbox1.addLayout(checkboxs) #----------------------------------------- irow = 0 grid1.addWidget(self.all_nodes_header, irow, 0) irow += 1 grid1.addWidget(self.color, irow, 0) grid1.addWidget(self.color_edit, irow, 1) irow += 1 grid1.addWidget(self.opacity, irow, 0) grid1.addWidget(self.opacity_edit, irow, 1) irow += 1 grid1.addWidget(self.point_size, irow, 0) grid1.addWidget(self.point_size_edit, irow, 1) irow += 1 #----------------------------------------- irow = 0 grid2.addWidget(self.nodes_header, irow, 0) irow += 1 grid2.addWidget(self.name, irow, 0) grid2.addWidget(self.name_edit, irow, 1) irow += 1 grid2.addWidget(self.description, irow, 0) grid2.addWidget(self.description_edit, irow, 1) irow += 1 #| All Nodes: | #| Color red | #| PointSize 3 | #| Opacity 0.3 | #| Show/Hide | #| | #| Name LEwingTip | #| Location X Y Z | #| Coord 0 | #| CoordType R, C, S | #| | #| Previous Next | grid2.addWidget(self.coord, irow, 0) grid2.addWidget(self.coord_edit, irow, 1) irow += 1 grid2.addWidget(self.coord_type, irow, 0) grid2.addLayout(coord_type_layout, irow, 1) irow += 1 grid2.addWidget(self.location, irow, 0) grid2.addLayout(location_layout, irow, 1) irow += 1 #------------------------------------ vbox = QVBoxLayout() vbox.addLayout(grid1) vbox.addLayout(vbox1) vbox.addStretch() vbox.addWidget(self.table) vbox.addLayout(grid2) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(cancel_box) self.setLayout(vbox) def set_connections(self): if qt_version == 4: self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show) self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide) self.connect(self.description_edit, QtCore.SIGNAL("valueChanged(int)"), self.on_description) self.connect(self.coord_edit, QtCore.SIGNAL("valueChanged(int)"), self.on_coord) self.connect(self.radio_rectangular, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.radio_cylindrical, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.radio_spherical, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.location_x_edit, QtCore.SIGNAL('clicked()'), self.on_location_x) self.connect(self.location_y_edit, QtCore.SIGNAL('clicked()'), self.on_location_y) self.connect(self.location_z_edit, QtCore.SIGNAL('clicked()'), self.on_location_z) self.connect(self.close_button, QtCore.SIGNAL('clicked()'), self.on_close) #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) #self.connect(self.close_button, QtCore.SIGNAL('clicked()'), self.on_close) else: pass #self.opacity_edit.clicked.connect(self.on_opacity) #self.point_size.clicked.connect(self.on_point_size) #self.color_edit.clicked.connect(self.on_color) #self.checkbox_show.clicked.connect(self.on_show) #self.checkbox_hide.clicked.connect(self.on_hide) #self.description_edit.valueChanged.connect(self.on_description) #self.coord_edit.valueChanged.connect(self.on_coord) #self.radio_rectangular.clicked.connect(self.on_coord_type) #self.radio_cylindrical.clicked.connect(self.on_coord_type) #self.radio_spherical.clicked.connect(self.on_coord_type) #self.location_x_edit.clicked.connect(self.on_location_x) #self.location_y_edit.clicked.connect(self.on_location_y) #self.location_z_edit.clicked.connect(self.on_location_z) self.close_button.clicked.connect(self.on_close) def on_color(self): obj = self.out_data['point_properties'] rgb_color_ints = obj.color msg = 'Points' col = QColorDialog.getColor(QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color = col.getRgbF()[:3] obj.color = color #print('new_color =', color) self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") def on_show(self): is_checked = self.checkbox_show.isChecked() self.out_data['point_properties'].is_visible = is_checked def on_hide(self): is_checked = self.checkbox_hide.isChecked() self.out_data['point_properties'].is_visible = not is_checked def on_point_size(self): point_size = self.point_size_edit.value() self.out_data['point_properties'].point_size = point_size def on_opacity(self): opacity = self.opacity_edit.value() self.out_data['point_properties'].opacity = opacity def on_description(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key description = self.description_edit.value() self.out_data['points'][name][0] = description def on_coord(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key coord_id = self.coord_edit.value() self.out_data['points'][name][1] = coord_id def on_coord_type(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key if self.radio_rectangular.isChecked(): coord_type = 'R' elif self.radio_cylindrical.isChecked(): coord_type = 'C' elif self.radio_spherical.isChecked(): coord_type = 'S' else: raise NotImplementedError() self.out_data['points'][name][2] = coord_type def on_location_x(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][3] = value def on_location_y(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][4] = value def on_location_z(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][5] = value def closeEvent(self, event): event.accept() #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.point_size = self.point_size_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self): passed = self.on_validate() if passed: self.win_parent.on_update_gui_nodes(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_close(self): self.out_data['clicked_close'] = True self.close()
class TemplateWindow(QMainWindow): def __init__(self, params_pipe, number_pipe, templates_pipe, spikes_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = [] self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 100.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': -200, # µV 'max': 20e+1, # µV 'init': 50.0, # µV }, 'templates': self._display_list } self._canvas_mea = MEACanvas(probe_path=probe_path, params=self._params) self._canvas_template = TemplateCanvas(probe_path=probe_path, params=self._params) self._canvas_rate = RateCanvas(probe_path=probe_path, params=self._params) self._canvas_isi = ISICanvas(probe_path=probe_path, params=self._params) self.cells = Cells({}) self._nb_buffer = 0 # TODO ISI self.isi_bin_width, self.isi_x_max = 2, 25.0 canvas_template_widget = self._canvas_template.native canvas_mea = self._canvas_mea.native canvas_rate = self._canvas_rate.native canvas_isi = self._canvas_isi.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) label_binsize = QLabel() label_binsize.setText(u"Bin size") label_binsize_unit = QLabel() label_binsize_unit.setText(u"second") self._dsp_binsize = QDoubleSpinBox() self._dsp_binsize.setRange(0.1, 10) self._dsp_binsize.setSingleStep(0.1) self.bin_size = 1 self._dsp_binsize.setValue(self.bin_size) self._dsp_binsize.valueChanged.connect(self._on_binsize_changed) label_zoomrates = QLabel() label_zoomrates.setText(u'Zoom rates') self._zoom_rates = QDoubleSpinBox() self._zoom_rates.setRange(1, 50) self._zoom_rates.setSingleStep(0.1) self._zoom_rates.setValue(1) self._zoom_rates.valueChanged.connect(self._on_zoomrates_changed) label_time_window = QLabel() label_time_window.setText(u'Time window rates') label_time_window_unit = QLabel() label_time_window_unit.setText(u'second') self._dsp_tw_rate = QDoubleSpinBox() self._dsp_tw_rate.setRange(1, 50) self._dsp_tw_rate.setSingleStep(self.bin_size) self._dsp_tw_rate.setValue(50 * self.bin_size) self._dsp_tw_rate.valueChanged.connect(self._on_time_window_changed) label_tw_from_start = QLabel() label_tw_from_start.setText('Time scale from start') self._tw_from_start = QCheckBox() self._tw_from_start.setChecked(True) self._selection_templates = QTableWidget() self._selection_templates.setSelectionMode( QAbstractItemView.ExtendedSelection ) self._selection_templates.setColumnCount(3) self._selection_templates.setVerticalHeaderLabels(['Nb template', 'Channel', 'Amplitude']) self._selection_templates.insertRow(0) self._selection_templates.setItem(0, 0, QTableWidgetItem('Nb template')) self._selection_templates.setItem(0, 1, QTableWidgetItem('Channel')) self._selection_templates.setItem(0, 2, QTableWidgetItem('Amplitude')) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) # for i in range(self.nb_templates): # numRows = self.tableWidget.rowCount() # self.tableWidget.insertRow(numRows) # item = QTableWidgetItem("Template %i" % i) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add binsize row. grid.addWidget(label_binsize, 2, 0) grid.addWidget(self._dsp_binsize, 2, 1) grid.addWidget(label_binsize_unit, 2, 2) # # Add zoom rate grid.addWidget(label_zoomrates, 3, 0) grid.addWidget(self._zoom_rates, 3, 1) # Add a double checkbox for time window grid.addWidget(label_time_window, 4, 0) grid.addWidget(self._dsp_tw_rate, 4, 1) grid.addWidget(label_time_window_unit, 4, 2) ## Add checkbox to display the rates from start grid.addWidget(label_tw_from_start, 5, 0) grid.addWidget(self._tw_from_start, 5, 1) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) # Create info grid. templates_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) templates_grid.addWidget(self._selection_templates, 0, 1) def add_template(): items = self._selection_templates.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_templates_changed() # self._selection_templates.itemClicked.connect(add_template) # Template selection signals self._selection_templates.itemSelectionChanged.connect(lambda: self.selected_templates( self.nb_templates)) # Checkbox to display all the rates self._tw_from_start.stateChanged.connect(self.time_window_rate_full) # self._selection_templates.itemPressed(0, 1).connect(self.sort_template()) # # Add spacer. templates_grid.addItem(spacer) # Create controls group. templates_group = QGroupBox() templates_group.setLayout(templates_grid) # # Create controls dock. templates_dock = QDockWidget() templates_dock.setWidget(templates_group) templates_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, templates_pipe, spikes_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, templates_dock) # Add Grid Layout for canvas canvas_grid = QGridLayout() group_canv_temp = QDockWidget() group_canv_temp.setWidget(canvas_template_widget) group_canv_mea = QDockWidget() group_canv_mea.setWidget(canvas_mea) group_canv_rate = QDockWidget() group_canv_rate.setWidget(canvas_rate) group_canv_isi = QDockWidget() group_canv_isi.setWidget(canvas_isi) canvas_grid.addWidget(group_canv_temp, 0, 0) canvas_grid.addWidget(group_canv_mea, 0, 1) canvas_grid.addWidget(group_canv_rate, 1, 1) canvas_grid.addWidget(group_canv_isi, 1, 0) canvas_group = QGroupBox() canvas_group.setLayout(canvas_grid) # Set central widget. self.setCentralWidget(canvas_group) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove? @property def nb_templates(self): return len(self.cells) def _number_callback(self, number): self._nb_buffer = float(number) text = u"{}".format(number) self._info_buffer_value_label.setText(text) text = u"{:8.3f}".format(self._nb_buffer * float(self._nb_samples) / self._sampling_rate) self._label_time_value.setText(text) return def _reception_callback(self, templates, spikes): bar = None if templates is not None: bar = [] for i in range(len(templates)): mask = spikes['templates'] == i template = load_template_from_dict(templates[i], self.probe) new_cell = Cell(template, Train([]), Amplitude([], [])) self.cells.append(new_cell) self._selection_templates.insertRow(self.nb_templates) bar += [template.center_of_mass(self.probe)] channel = template.channel amplitude = template.peak_amplitude() # self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem("Template %d" %self.nb_templates)) # self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(bar))) self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem(str(self.nb_templates))) self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(channel))) self._selection_templates.setItem(self.nb_templates, 2, QTableWidgetItem(str(amplitude))) # item = QListWidgetItem("Template %i" % self.nb_templates) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) # self.nb_templates += 1 # print(bar.shape, bar) if spikes is not None: self.cells.add_spikes(spikes['spike_times'], spikes['amplitudes'], spikes['templates']) self.cells.set_t_max(self._nb_samples * self._nb_buffer / self._sampling_rate) to_display = self.cells.rate(self.bin_size) self._canvas_template.on_reception(templates, self.nb_templates) self._canvas_mea.on_reception_bary(bar, self.nb_templates) # TODO Cells rate self._canvas_rate.on_reception_rates(self.cells.rate(self.bin_size)) # TODO : ISI If we want to display the ISI also # isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max=25.0) isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max) self._canvas_isi.on_reception_isi(isi) return def _on_time_changed(self): time = self._dsp_time.value() self._canvas_template.set_time(time) self._dsp_tw_rate.setRange(1, int(time)) return def _on_binsize_changed(self): time = self._dsp_binsize.value() self.bin_size = time self._dsp_tw_rate.setSingleStep(self.bin_size) return def _on_zoomrates_changed(self): zoom_value = self._zoom_rates.value() self._canvas_rate.zoom_rates(zoom_value) return def _on_voltage_changed(self): voltage = self._dsp_voltage.value() self._canvas_template.set_voltage(voltage) return def _on_peaks_display(self): value = self._display_peaks.isChecked() self._canvas_template.show_peaks(value) return def _on_templates_changed(self): self._canvas_template.set_templates(self._display_list) return def selected_templates(self, max_templates): list_templates = [] list_channels = [] for i in range(max_templates + 1): if i != 0 and \ self._selection_templates.item(i, 0).isSelected() and \ self._selection_templates.item(i, 1).isSelected() and \ self._selection_templates.item(i, 2).isSelected(): list_templates.append(i - 1) list_channels.append(int(self._selection_templates.item(i, 1).text())) self._canvas_template.selected_templates(list_templates) self._canvas_mea.selected_channels(list_channels) self._canvas_mea.selected_templates(list_templates) self._canvas_rate.selected_cells(list_templates) self._canvas_isi.selected_cells(list_templates) return def time_window_rate_full(self): value = self._tw_from_start.isChecked() self._canvas_rate.time_window_full(value) return def _on_time_window_changed(self): tw_value = self._dsp_tw_rate.value() self._canvas_rate.time_window_value(tw_value, self.bin_size) return
class dbsElectrodeControlsDialog(QDialog): def __init__(self, callback, parent=None): QDialog.__init__(self, parent) self.callback = callback self.create_widgets() #self.layout_widgets() self.create_connections() self.setModal(False) self.setWindowTitle('Electrode Controls') self.layout().setSizeConstraint(QLayout.SetFixedSize) self.saved_params = dict() def create_widgets(self): gridLayout = QGridLayout() groupBox = QGroupBox( 'Rendering controls' ) groupBox.setFlat(True) groupBox2 = QGroupBox( 'DBSCAN centroids' ) groupBox2.setFlat(True) groupBox3 = QGroupBox( 'Electrode filter' ) groupBox3.setFlat(True) gridLayout.addWidget(groupBox) gridLayout.addWidget(groupBox3) gridLayout.addWidget(groupBox2) # rendering controls self.visi_label = QLabel( 'show electrodes' ) self.visi = QCheckBox() self.visi.setChecked(False) self.fall_off_label = QLabel( 'fall-off' ) self.fall_off = QSlider(Qt.Horizontal) self.fall_off.setRange(1, 100) # data set dependent self.thickness_label = QLabel( 'thickness' ) self.thickness = QSlider(Qt.Horizontal) self.thickness.setRange(1, 100) # data set dependent self.trans_label = QLabel( 'force translucency' ) self.forced_translucency = QCheckBox() self.forced_translucency.setChecked(False) # dbscan controls #self.view_button_grp = QButtonGroup() self.all_electrodes = QRadioButton('show all') self.only_clusters = QRadioButton('show clusters') self.only_noise = QRadioButton('show noise') self.all_electrodes.setEnabled(False) self.all_electrodes.setChecked(True) self.only_clusters.setEnabled(False) self.only_noise.setEnabled(False) #self.view_button_grp.addButton( self.all_electrodes ) #self.view_button_grp.addButton( self.only_clusters ) #self.view_button_grp.addButton( self.only_noise ) #gridLayout.addWidget(self.view_button_grp) self.eps_label = QLabel( 'epsilon' ) self.eps_spinbox = QDoubleSpinBox() self.eps_spinbox.setRange(0.1, 10) self.eps_spinbox.setSingleStep(0.1) self.min_points_label = QLabel( 'min points' ) self.min_spinbox = QSpinBox() self.min_spinbox.setRange(1, 20) self.min_spinbox.setSingleStep(1) self.button = QPushButton('Recalculate') self.button.setCheckable(True) self.browser = QTextBrowser() vbox = QVBoxLayout() vbox2 = QVBoxLayout() vbox3 = QVBoxLayout() vbox.addWidget( self.visi_label ) vbox.addWidget( self.visi ) vbox.addWidget( self.fall_off_label ) vbox.addWidget( self.fall_off ) vbox.addWidget( self.thickness_label ) vbox.addWidget( self.thickness ) vbox.addWidget( self.trans_label ) vbox.addWidget( self.forced_translucency ) vbox2.addWidget( self.eps_label ) vbox2.addWidget( self.eps_spinbox ) vbox2.addWidget( self.min_points_label ) vbox2.addWidget( self.min_spinbox ) vbox2.addWidget( self.button ) vbox2.addWidget( self.browser ) vbox3.addWidget( self.all_electrodes ) vbox3.addWidget( self.only_clusters ) vbox3.addWidget( self.only_noise ) groupBox.setLayout(vbox) groupBox2.setLayout(vbox2) groupBox3.setLayout(vbox3) self.setLayout(gridLayout) self.layout().setSizeConstraint( QLayout.SetFixedSize ) def create_connections(self): self.visi.stateChanged.connect(self.__toggleVisibility) self.fall_off.valueChanged.connect(self.__setOpacityFalloff) self.thickness.valueChanged.connect(self.__setLineThickness) self.forced_translucency.stateChanged.connect(self.__toggleForceTranslucency) self.button.pressed.connect(self.__calculateDBSCANClusters) self.all_electrodes.toggled.connect(self.__setElectrodeTypeVisible) self.only_clusters.toggled.connect(self.__setElectrodeTypeVisible) self.only_noise.toggled.connect(self.__setElectrodeTypeVisible) def __setElectrodeTypeVisible(self): av = self.parent().active_vol vdata = self.parent()._vdata[av] if self.all_electrodes.isChecked(): vdata.setAllElectrodesVisible() elif self.only_clusters.isChecked(): vdata.setElectrodeClustersVisible() elif self.only_noise.isChecked(): vdata.setElectrodeNoiseVisible() def __calculateDBSCANClusters(self): av = self.parent().active_vol vdata = self.parent()._vdata[av] vdata.setDBSCANEps( self.eps_spinbox.value() ) vdata.setDBSCANMinPts( self.min_spinbox.value() ) vdata.clusterWithDBSCAN() count = vdata.electrode_centroid_clustering.dbscan_clusters labels = vdata.electrode_centroid_clustering.dbscan_results.labels_ out = 'Estimated number of clusters: %d\n' % count #self.browser.setText('Estimated number of clusters: %d' % count) for patnum, score in enumerate(labels): out += 'Patient {0}: {1}\n'.format(patnum, score) self.browser.setText(out) vdata.setElectrodeClustersVisible() self.only_clusters.setChecked(True) def __toggleVisibility(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes on = False if self.visi.checkState(): on = True self.all_electrodes.setEnabled(True) self.only_clusters.setEnabled(True) self.only_noise.setEnabled(True) else: self.all_electrodes.setEnabled(False) self.only_clusters.setEnabled(False) self.only_noise.setEnabled(False) for electrode in vdata: electrode.setVis(on) self.apply() def __toggleForceTranslucency(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes on = False if self.forced_translucency.checkState(): on = True for electrode in vdata: electrode.forceTranslucency(on) self.apply() def __setOpacityFalloff(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes #self.fall_off.setValue( vdata[-1].fall_off ) for electrode in vdata: electrode.setFallOff(self.fall_off.value() / 10.0) self.apply() def __setLineThickness(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes for electrode in vdata: electrode.setThickness(self.thickness.value() / 10.0) self.apply() def saveCurrentParams(self, av, fresh_load = False): #av = self.parent().active_vol #vdata = self.parent()._vdata[av]._electrodes if av not in self.saved_params.keys(): self.saved_params[av] = ElectrodeParameters() self.saved_params[av].electrodes_show = self.visi.isChecked() self.saved_params[av].electrodes_all = self.all_electrodes.isChecked() self.saved_params[av].electrodes_clusters = self.only_clusters.isChecked() self.saved_params[av].electrodes_noise = self.only_noise.isChecked() self.saved_params[av].falloff = self.fall_off.value() self.saved_params[av].thickness = self.thickness.value() self.saved_params[av].transp = self.forced_translucency.isChecked() self.saved_params[av].fresh_load = fresh_load def updateWidgetValues(self, av, default = False): #av = self.parent().active_vol #vdata = self.parent()._vdata[av]._electrodes if av not in self.saved_params.keys(): self.saved_params[av] = ElectrodeParameters() if default: # todo: need to have default values in one place for assignment self.visi.setChecked( False ) self.all_electrodes.setChecked( False ) self.only_clusters.setChecked( False ) self.only_noise.setChecked( False ) self.fall_off.setValue( 1 ) self.thickness.setValue( 10 ) self.forced_translucency.setChecked( False ) else: self.visi.setChecked( self.saved_params[av].electrodes_show ) self.all_electrodes.setChecked( self.saved_params[av].electrodes_all ) self.only_clusters.setChecked( self.saved_params[av].electrodes_clusters ) self.only_noise.setChecked( self.saved_params[av].electrodes_noise ) self.fall_off.setValue( self.saved_params[av].falloff ) self.thickness.setValue( self.saved_params[av].thickness ) self.forced_translucency.setChecked( self.saved_params[av].transp ) def apply(self): av = self.parent().active_vol self.parent().vol_qvtk_widgets[av].update()
class ItemTreeWidget(GenericTreeWidget): def __init__(self, session, parent, creator): GenericTreeWidget.__init__(self, session, parent) self.creator = creator self.setTitle('Tuotteet') self.setButtons([ButtonType.add,ButtonType.open,ButtonType.remove]) self.setHeader(headertexts=['id', 'Nimi', 'Tyyppi', 'Hinta', 'Määrä'], hidecolumns=[0]) from mainwindowtabs.itemcreatordialog import ItemCreatorDialog self.setInputMethod(tabcreator=ItemCreatorDialog, autoAdd=True, function=SqlHandler.searchItem) self.countSpinBox = QDoubleSpinBox(parent=self) self.countSpinBox.setRange(0.01, 99999999) self.countSpinBox.setValue(1) if self.ui.topLayout.count() > 0 or self.ui.bottomLayout.count() == 0: self.ui.topLayout.insertWidget(self.ui.topLayout.count(), self.countSpinBox) else: self.ui.bottomLayout.incertWidget(self.ui.bottomLayout.count(), self.countSpinBox) self.setUpTreewidget() self.countSpinBox.valueChanged['double'].connect(self.updateItemCount) self.ui.treeWidget.currentItemChanged.connect(self.handleChange) def setUpTreewidget(self): if self.ui.treeWidget.currentItem() != None: #set item count to countSpinBox self.countSpinBox.setValue(self.ui.treeWidget.currentItem().data(0,0).count) def updateItemCount(self,count): current = self.ui.treeWidget.currentItem() if current.data(0,0).count != count: current.data(0,0).count = count current.setText(3, '%.2f' % (current.data(0,0).item.price*count)) current.setText(4, str(count)) def handleChange(self, current, previous): if current != None: self.countSpinBox.setValue(self.ui.treeWidget.currentItem().data(0,0).count) ''' This function is called when: 1. searchLineEdit returns new item (Item) 2. list of items is loaded from Surgery or SurgeryBase object 3. just wanted to increase count of current item. item is type of Item/SurgeryItem/SurgetyBaseItem ''' def addItemToTree(self, item): if item != None: if self.creator and item.getType() == self.creator.getType(): #Now we are loading data from Surgery or Surgery base object #So we make new tree objects and add counts to them treeItem = self.makeTreeItem(item) self.ui.treeWidget.addTopLevelItem(treeItem) self.ui.treeWidget.setCurrentItem(treeItem) else: item_index = self.itemInList(item) if item_index < 1: #Item isnt found from list so we make new treeItem = self.makeTreeItem(item) self.ui.treeWidget.addTopLevelItem(treeItem) self.ui.treeWidget.setCurrentItem(treeItem) else: #item is in list and it is just returned from Itemcreator and data is needed to be edited #or it it is tryed to add by searchline edit removedItem = self.ui.treeWidget.takeTopLevelItem(item_index) #take line from list item_data = item.stringList() #get item new string list #update data, only item data not for i in range(1,len(item_data)): removedItem.setText(i,item_data[i]) #set updated text to line self.ui.treeWidget.addTopLevelItem(removedItem) #add line back to list self.ui.treeWidget.setCurrentItem(removedItem) #set it current item def getItemsFromList(self): itemList = [] for i in range(0, self.ui.treeWidget.topLevelItemCount()): itemList.append(self.ui.treeWidget.topLevelItem(i).data(0,0)) return itemList def removeSelectedItem(self): temp = self.ui.treeWidget.currentItem() if temp != None: removedItem = self.ui.treeWidget.takeTopLevelItem(self.ui.treeWidget.indexOfTopLevelItem(temp)) if removedItem != None: item = removedItem.data(0,0) if item in self.session: self.session.delete(item) def openItem(self): tree_item = self.ui.treeWidget.currentItem() if tree_item != None: creator = self.tabcreator(parent=self, item=tree_item.data(0,0).item) creator.show() ''' item is Item(any of them) or SurgeryItem/SurgeryBaseItem if creator is None it means that we should add item as it is ''' def makeTreeItem(self,item): if self.creator and item.getType() != self.creator.getType(): item = self.creator(item) #make new item textString = item.stringList() #has all info treeItem = QTreeWidgetItem(self.ui.treeWidget, textString) treeItem.setData(0,0,item) return treeItem def itemInList(self, item): if self.creator and item.getType() == self.creator.getType(): #get item from SurgeryBaseItem/SurgeryItem item = item.item for i in range(0, self.ui.treeWidget.topLevelItemCount()): temp_item = self.ui.treeWidget.topLevelItem(i).data(0,0) if temp_item.item.id == item.id: return i #item not found return -1
class AnimationWindow(PyDialog): """ +-------------------+ | Animation | +-------------------------+ | icase ______ | | scale ______ Default | | time ______ Default | | | | nframes ______ Default | | resolu. ______ Default | | Dir ______ Browse | | iFrame ______ | | | | Animations: | | o Scale, Phase, Time | # TODO: add time | | | x delete images | | x repeat | # TODO: change to an integer | x make gif | | | | Step, RunAll | | Close | +-------------------------+ TODO: add key-frame support """ def __init__(self, data, win_parent=None): PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) self.istep = 0 self._animate_type = 'time' self._updated_animation = False self._icase = data['icase'] self._default_name = data['name'] self._default_time = data['time'] self._default_fps = data['frames/sec'] self._default_resolution = data['resolution'] self._scale = data['scale'] self._default_scale = data['default_scale'] self._default_is_scale = data['is_scale'] self._phase = data['phase'] self._default_phase = data['default_phase'] self._default_dirname = data['dirname'] self._default_gif_name = os.path.join(self._default_dirname, data['name'] + '.gif') self.animation_types = [ 'Animate Scale', ] #'Animate Phase', #'Animate Time', #'Animate Frequency Sweep' #] self.setWindowTitle('Animate Model') self.create_widgets() self.create_layout() self.set_connections() self.is_gui = False if hasattr(self.win_parent, '_updated_legend'): self.win_parent.is_animate_open = True self.is_gui = True def create_widgets(self): """creates the menu objects""" icase_max = 1000 # TODO: update 1000 self.icase = QLabel("iCase:") self.icase_edit = QSpinBox(self) self.icase_edit.setRange(1, icase_max) self.icase_edit.setSingleStep(1) self.icase_edit.setValue(self._icase) self.icase_edit.setToolTip( 'Case Number for the Scale/Phase Animation Type.\n' 'Defaults to the result you had shown when you clicked "Create Animation".\n' 'iCase can be seen by clicking "Apply" on a result.') self.scale = QLabel("Scale:") self.scale_edit = QLineEdit(str(self._scale)) self.scale_button = QPushButton("Default") self.scale_edit.setToolTip('Scale factor of the "deflection"') self.scale_button.setToolTip('Sets the scale factor of the gif to %s' % self._scale) self.time = QLabel("Total Time (sec):") self.time_edit = QDoubleSpinBox(self) self.time_edit.setValue(self._default_time) self.time_edit.setRange(0.1, 10.0) self.time_edit.setDecimals(2) self.time_edit.setSingleStep(0.1) self.time_button = QPushButton("Default") self.time_edit.setToolTip("Total time of the gif") self.time_button.setToolTip('Sets the total time of the gif to %.2f' % self._default_time) self.fps = QLabel("Frames/Second:") self.fps_edit = QSpinBox(self) self.fps_edit.setRange(1, 60) self.fps_edit.setSingleStep(1) self.fps_edit.setValue(self._default_fps) self.fps_button = QPushButton("Default") self.fps_edit.setToolTip( "A higher FPS is smoother, but may not play well for large gifs") self.fps_button.setToolTip('Sets the FPS to %s' % self._default_fps) self.resolution = QLabel("Resolution Scale:") self.resolution_edit = QSpinBox(self) self.resolution_edit.setRange(1, 5) self.resolution_edit.setSingleStep(1) self.resolution_edit.setValue(self._default_resolution) self.resolution_button = QPushButton("Default") self.resolution_edit.setToolTip( 'Scales the window resolution by an integer factor') self.resolution_button.setToolTip('Sets the resolution to %s' % self._default_resolution) #----------------- # Time plot self.icase_start = QLabel("iCase Start:") self.icase_start_edit = QSpinBox(self) self.icase_start_edit.setRange(0, icase_max) self.icase_start_edit.setSingleStep(1) self.icase_start_edit.setValue(self._icase) self.icase_start_button = QPushButton("Default") self.icase_end = QLabel("iCase End:") self.icase_end_edit = QSpinBox(self) self.icase_end_edit.setRange(0, icase_max) self.icase_end_edit.setSingleStep(1) self.icase_end_edit.setValue(self._icase) self.icase_end_button = QPushButton("Default") self.icase_delta = QLabel("iCase Delta:") self.icase_delta_edit = QSpinBox(self) self.icase_delta_edit.setRange(1, icase_max) self.icase_delta_edit.setSingleStep(1) self.icase_delta_edit.setValue(1) self.icase_delta_button = QPushButton("Default") self.min_value = QLabel("Min Value:") self.min_value_edit = QLineEdit(str(0.)) #self.min_value_edit.setRange(1, 1000) #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.min_value_button = QPushButton("Default") self.max_value = QLabel("Max Value:") self.max_value_edit = QLineEdit(str(1.)) #self.min_value_edit.setRange(1, 1000) # TODO: update 1000 #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.max_value_button = QPushButton("Default") self.icase_start_edit.setToolTip('The first frame of the animation') self.icase_end_edit.setToolTip( 'The last frame of the animation\n' 'Assumes icase_start + nframes * icase_delta = icase_end') self.icase_delta_edit.setToolTip( 'The frame step size (to skip non-consecutive results).\n' 'Frame skipping can be used to:\n' " - skip across results that you don't want to plot\n" ' - adjust the FPS') self.min_value_edit.setToolTip( 'Min value of the legend (not supported)') self.max_value_edit.setToolTip( 'Max value of the legend (not supported)') #'time' : 0., #'default_time' : 0, #'icase_start' : 10, #'icase_delta' : 3, #'min_value' : 0., #'max_value' : 1000., self.browse_folder = QLabel('Output Directory:') self.browse_folder_edit = QLineEdit(str(self._default_dirname)) self.browse_folder_button = QPushButton('Browse') self.browse_folder_edit.setToolTip( 'Location to save the png/gif files') self.gif = QLabel("Gif Filename:") self.gif_edit = QLineEdit(str(self._default_name + '.gif')) self.gif_button = QPushButton('Default') self.gif_edit.setToolTip('Name of the gif') self.gif_button.setToolTip('Sets the name of the gif to %s.gif' % self._default_name) # scale / phase self.animate_scale_radio = QRadioButton("Animate Scale") self.animate_phase_radio = QRadioButton("Animate Phase") self.animate_time_radio = QRadioButton("Animate Time") self.animate_freq_sweeep_radio = QRadioButton( "Animate Frequency Sweep") self.animate_scale_radio.setToolTip( 'Animates the scale factor based on the "Animation Type"') self.animate_time_radio.setToolTip('Animates the time/load/mode step') self.animate_scale_radio.setChecked(self._default_is_scale) self.animate_phase_radio.setChecked(not self._default_is_scale) self.animate_time_radio.setChecked(False) msg = 'Scale : Animates the scale factor based on the "Animation Profile"\n' if self._default_phase is None: self.animate_phase_radio.setDisabled(True) self.animate_phase_radio.setToolTip('Animates the phase angle ' '(only for complex results)') msg += 'Phase : Animates the phase angle (only for complex results)\n' else: self.animate_phase_radio.setToolTip("Animates the phase angle") msg += 'Phase : Animates the phase angle\n' msg += ( 'Time : Animates the time/load/mode step\n' 'Freq Sweep : Animates a complex result across a range of frequencies ' '(not supported)\n') self.animate_freq_sweeep_radio.setDisabled(True) self.animate_freq_sweeep_radio.setToolTip( 'Animates a complex result across a range of frequencies (not supported)' ) self.animation_type = QLabel("Animation Type:") animation_type = OrderedDict() #scale_msg = 'Scale\n' #phase_msg = 'Phase\n' #time_msg = 'Time\n' #animation_types = [ #('Animate Scale', scale_msg), #('Animate Phase', phase_msg), #('Animate Time', time_msg), ##'Animate Frequency Sweep' #] if self._phase is not None: self.animation_types.append('Animate Phase') self.animation_types.append('Animate Time') self.animation_profile = QLabel("Animation Profile:") self.animation_profile_edit = QComboBox() for animation_profile in ANIMATION_PROFILES: self.animation_profile_edit.addItem(animation_profile) self.animation_profile_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit = QComboBox() # TODO: add a tooltip for each item for animation_type in self.animation_types: self.animation_type_edit.addItem(animation_type) #self.animation_type_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit.setToolTip(msg) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_browse_button = QPushButton('Browse') self.csv_profile_edit.setToolTip( 'The path to the CSV file of (Scale1, Scale2, Scale3, ...)') widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.animate_scale_radio) horizontal_vertical_group.addButton(self.animate_phase_radio) horizontal_vertical_group.addButton(self.animate_time_radio) horizontal_vertical_group.addButton(self.animate_freq_sweeep_radio) # one / two sided self.onesided_radio = QRadioButton("One Sided") self.onesided_radio.setToolTip( "A one sided gif doesn't return to the starting point (e.g., 0 to 360 degrees)" ) self.twosided_radio = QRadioButton("Two Sided") self.twosided_radio.setToolTip( 'A two sided gif returns to the starting point (e.g., 0 to 10 to 0)' ) if self._default_phase is None: self.onesided_radio.setChecked(False) self.twosided_radio.setChecked(True) else: self.onesided_radio.setChecked(True) self.twosided_radio.setChecked(False) widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.onesided_radio) horizontal_vertical_group.addButton(self.twosided_radio) # animate in gui self.animate_in_gui_checkbox = QCheckBox("Animate In GUI?") self.animate_in_gui_checkbox.setChecked(True) # make images self.make_images_checkbox = QCheckBox("Make images?") self.make_images_checkbox.setChecked(True) # make images self.overwrite_images_checkbox = QCheckBox("Overwrite images?") self.overwrite_images_checkbox.setChecked(True) # delete images when finished self.delete_images_checkbox = QCheckBox("Delete images when finished?") self.delete_images_checkbox.setChecked(True) # endless loop self.repeat_checkbox = QCheckBox("Repeat?") self.repeat_checkbox.setChecked(True) self.repeat_checkbox.setToolTip( "Repeating creates an infinitely looping gif") # endless loop self.make_gif_checkbox = QCheckBox("Make Gif?") if IS_IMAGEIO: self.make_gif_checkbox.setChecked(True) else: self.make_gif_checkbox.setChecked(False) self.make_gif_checkbox.setEnabled(False) self.make_gif_checkbox.setToolTip( 'imageio is not available; install it') # bottom buttons self.step_button = QPushButton("Step") self.stop_button = QPushButton("Stop") self.run_button = QPushButton("Run All") #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") #self.set_grid_time(enabled=False) #self.set_grid_scale(enabled=self._default_is_scale) if self._default_phase: self.on_animate_phase(force=True) else: self.on_animate_scale(force=True) def set_connections(self): """creates button actions""" self.scale_button.clicked.connect(self.on_default_scale) self.time_button.clicked.connect(self.on_default_time) self.fps_button.clicked.connect(self.on_default_fps) self.resolution_button.clicked.connect(self.on_default_resolution) self.browse_folder_button.clicked.connect(self.on_browse_folder) self.csv_profile_browse_button.clicked.connect(self.on_browse_csv) self.gif_button.clicked.connect(self.on_default_name) self.step_button.clicked.connect(self.on_step) self.stop_button.clicked.connect(self.on_stop) self.run_button.clicked.connect(self.on_run) #self.animate_scale_radio.clicked.connect(self.on_animate_scale) #self.animate_phase_radio.clicked.connect(self.on_animate_phase) #self.animate_time_radio.clicked.connect(self.on_animate_time) self.animation_type_edit.currentIndexChanged.connect(self.on_animate) #self.animate_freq_sweeep_radio #self.apply_button.clicked.connect(self.on_apply) #self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) self.animate_in_gui_checkbox.clicked.connect(self.on_animate_in_gui) self.animate_in_gui_checkbox.setChecked(True) self.on_animate_in_gui() def on_animate_in_gui(self): animate_in_gui = self.animate_in_gui_checkbox.isChecked() enable = not animate_in_gui self.make_images_checkbox.setEnabled(enable) self.delete_images_checkbox.setEnabled(enable) self.make_gif_checkbox.setEnabled(enable) self.repeat_checkbox.setEnabled(enable) self.resolution_button.setEnabled(enable) self.resolution_edit.setEnabled(enable) self.gif_edit.setEnabled(enable) self.gif_button.setEnabled(enable) self.browse_folder_button.setEnabled(enable) self.browse_folder_edit.setEnabled(enable) self.step_button.setEnabled(enable) def on_animate(self, value): """ animate pulldown Parameters ---------- value : int index in animation_types """ #animation_types = ['Animate Scale', 'Animate Phase', 'Animate Time', #'Animate Frequency Sweep'] animation_type = self.animation_types[value] if animation_type == 'Animate Scale': self.on_animate_scale() elif animation_type == 'Animate Phase': self.on_animate_phase() elif animation_type == 'Animate Time': self.on_animate_time() else: raise NotImplementedError('value = ', value) def on_animate_time(self, force=False): """enables the secondary input""" #print('on_animate_time') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'time') self.set_grid_time(True, 'time') self._animate_type = 'time' def on_animate_scale(self, force=False): """enables the secondary input""" #print('on_animate_scale') self.set_grid_scale(True, 'scale') if self._animate_type == 'time' or force: self.set_grid_time(False, 'scale') self._animate_type = 'scale' def on_animate_phase(self, force=False): """enables the secondary input""" #print('on_animate_phase') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'phase') if self._animate_type == 'time' or force: self.set_grid_time(False, 'phase') self._animate_type = 'phase' def set_grid_scale(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_scale; enabled = %r' % (word, enabled)) self.animation_profile.setEnabled(enabled) self.animation_profile_edit.setEnabled(enabled) # TODO: doesn't work... #self.csv_profile.setEnabled(enabled) #self.csv_profile_edit.setEnabled(enabled) #self.csv_profile_button.setEnabled(enabled) def set_grid_time(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_time; enabled = %r' % (word, enabled)) self.icase_start.setEnabled(enabled) self.icase_start_edit.setEnabled(enabled) self.icase_start_button.setEnabled(enabled) self.icase_end.setEnabled(enabled) self.icase_end_edit.setEnabled(enabled) self.icase_end_button.setEnabled(enabled) self.icase_delta.setEnabled(enabled) self.icase_delta_edit.setEnabled(enabled) self.icase_delta_button.setEnabled(enabled) self.min_value.setEnabled(enabled) self.min_value_edit.setEnabled(enabled) self.min_value_button.setEnabled(enabled) self.max_value.setEnabled(enabled) self.max_value_edit.setEnabled(enabled) self.max_value_button.setEnabled(enabled) self.icase.setEnabled(not enabled) self.icase_edit.setEnabled(not enabled) self.fps.setEnabled(not enabled) self.fps_edit.setEnabled(not enabled) self.fps_button.setEnabled(not enabled) def on_browse_folder(self): """opens a folder dialog""" dirname = open_directory_dialog(self, 'Select a Directory') if not dirname: return self.browse_folder_edit.setText(dirname) def on_browse_csv(self): """opens a file dialog""" default_filename = '' file_types = 'Delimited Text (*.txt; *.dat; *.csv)' dirname = open_file_dialog(self, 'Select a CSV File', default_filename, file_types) if not dirname: return self.csv_profile_browse_button.setText(dirname) def on_default_name(self): """sets the default gif name""" self.gif_edit.setText(self._default_name + '.gif') def on_default_scale(self): """sets the default displacement scale factor""" self.scale_edit.setText(str(self._default_scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_time(self): """sets the default gif time""" self.time_edit.setValue(self._default_time) def on_default_fps(self): """sets the default FPS""" self.fps_edit.setValue(self._default_fps) def on_default_resolution(self): """sets the default image resolution scale factor""" self.resolution_edit.setValue(self._default_resolution) def create_layout(self): """displays the menu objects""" grid = QGridLayout() grid.addWidget(self.icase, 0, 0) grid.addWidget(self.icase_edit, 0, 1) grid.addWidget(self.scale, 1, 0) grid.addWidget(self.scale_edit, 1, 1) grid.addWidget(self.scale_button, 1, 2) grid.addWidget(self.time, 2, 0) grid.addWidget(self.time_edit, 2, 1) grid.addWidget(self.time_button, 2, 2) # spacer spacer = QLabel('') grid.addWidget(self.fps, 3, 0) grid.addWidget(self.fps_edit, 3, 1) grid.addWidget(self.fps_button, 3, 2) grid.addWidget(self.resolution, 4, 0) grid.addWidget(self.resolution_edit, 4, 1) grid.addWidget(self.resolution_button, 4, 2) grid.addWidget(self.browse_folder, 5, 0) grid.addWidget(self.browse_folder_edit, 5, 1) grid.addWidget(self.browse_folder_button, 5, 2) grid.addWidget(self.gif, 6, 0) grid.addWidget(self.gif_edit, 6, 1) grid.addWidget(self.gif_button, 6, 2) grid.addWidget(self.animation_type, 7, 0) grid.addWidget(self.animation_type_edit, 7, 1) grid.addWidget(spacer, 8, 0) #---------- #Time grid_time = QGridLayout() grid_time.addWidget(self.icase_start, 0, 0) grid_time.addWidget(self.icase_start_edit, 0, 1) #grid_time.addWidget(self.icase_start_button, 0, 2) grid_time.addWidget(self.icase_end, 1, 0) grid_time.addWidget(self.icase_end_edit, 1, 1) #grid_time.addWidget(self.icase_end_button, 1, 2) grid_time.addWidget(self.icase_delta, 2, 0) grid_time.addWidget(self.icase_delta_edit, 2, 1) #grid_time.addWidget(self.icase_delta_button, 2, 2) #grid_time.addWidget(self.min_value, 3, 0) #grid_time.addWidget(self.min_value_edit, 3, 1) #grid_time.addWidget(self.min_value_button, 3, 2) #grid_time.addWidget(self.max_value, 4, 0) #grid_time.addWidget(self.max_value_edit, 4, 1) #grid_time.addWidget(self.max_value_button, 4, 2) grid_time.addWidget(spacer, 5, 0) #-------------- grid_scale = QGridLayout() grid_scale.addWidget(self.animation_profile, 0, 0) grid_scale.addWidget(self.animation_profile_edit, 0, 1) #grid_scale.addWidget(self.csv_profile, 1, 0) #grid_scale.addWidget(self.csv_profile_edit, 1, 1) #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_button = QPushButton('Browse') #box_time = QVBoxLayout() # TODO: It's super annoying that the animate time box doesn't # line up with the previous box box_scale = QGroupBox('Animate Scale') box_scale.setLayout(grid_scale) box_time = QGroupBox('Animate Time') box_time.setLayout(grid_time) #---------- grid2 = QGridLayout() #grid2.addWidget(self.animate_scale_radio, 8, 0) #grid2.addWidget(self.animate_phase_radio, 8, 1) #grid2.addWidget(self.animate_time_radio, 8, 2) #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3) grid2.addWidget(self.animate_in_gui_checkbox, 10, 0) grid2.addWidget(self.make_images_checkbox, 11, 0) #grid2.addWidget(self.overwrite_images_checkbox, 11, 0) grid2.addWidget(self.delete_images_checkbox, 11, 1) grid2.addWidget(self.make_gif_checkbox, 11, 2) grid2.addWidget(self.repeat_checkbox, 12, 0) grid2.addWidget(spacer, 13, 0) grid_hbox = QHBoxLayout() grid_hbox.addWidget(spacer) grid_hbox.addLayout(grid2) grid_hbox.addWidget(spacer) # bottom buttons step_run_box = QHBoxLayout() step_run_box.addWidget(self.step_button) step_run_box.addWidget(self.stop_button) step_run_box.addWidget(self.run_button) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addWidget(box_scale) vbox.addWidget(box_time) #vbox.addLayout(checkboxes) vbox.addLayout(grid_hbox) vbox.addStretch() vbox.addLayout(step_run_box) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def on_step(self): """click the Step button""" passed, validate_out = self.on_validate() if passed: try: self._make_gif(validate_out, istep=self.istep) self.istep += 1 except IndexError: self._make_gif(validate_out, istep=0) self.istep += 1 def on_stop(self): passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, stop_animation=True) def on_run(self): """click the Run button""" self.istep = 0 passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, istep=None) return passed def _make_gif(self, validate_out, istep=None, stop_animation=False): """interface for making the gif""" icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase = validate_out gif_filename = None if not stop_animation and not animate_in_gui: if gifbase.lower().endswith('.gif'): gifbase = gifbase[:-4] gif_filename = os.path.join(output_dir, gifbase + '.gif') animate_scale = self.animate_scale_radio.isChecked() animate_phase = self.animate_phase_radio.isChecked() animate_time = self.animate_time_radio.isChecked() animate_scale = False animate_phase = False animate_time = False if self._animate_type == 'scale': animate_scale = True elif self._animate_type == 'phase': animate_phase = True elif self._animate_type == 'time': animate_time = True else: raise NotImplementedError(self._animate_type) make_images = self.make_images_checkbox.isChecked() delete_images = self.delete_images_checkbox.isChecked() make_gif = self.make_gif_checkbox.isChecked() key = str(self.animation_profile_edit.currentText()) #profile = ANIMATION_PROFILES[key] #ANIMATION_PROFILES['0 to Scale'] = [0., 1.] #ANIMATION_PROFILES['0 to Scale to 0'] = [0., 1., 0.] if key == '0 to Scale': onesided = True else: onesided = False icase_start = self.icase_start_edit.value() icase_end = self.icase_end_edit.value() icase_delta = self.icase_delta_edit.value() #onesided = self.onesided_radio.isChecked() bool_repeat = self.repeat_checkbox.isChecked( ) # TODO: change this to an integer if bool_repeat: nrepeat = 0 else: nrepeat = 1 #self.out_data['is_shown'] = self.show_radio.isChecked() #icase = self._icase if self.is_gui: self.win_parent.win_parent.make_gif( gif_filename, scale, istep=istep, animate_scale=animate_scale, animate_phase=animate_phase, animate_time=animate_time, icase=icase, icase_start=icase_start, icase_end=icase_end, icase_delta=icase_delta, time=time, onesided=onesided, nrepeat=nrepeat, fps=fps, magnify=magnify, make_images=make_images, delete_images=delete_images, make_gif=make_gif, stop_animation=stop_animation, animate_in_gui=animate_in_gui, ) self.out_data['clicked_ok'] = True self.out_data['close'] = True def on_validate(self): """checks to see if the input is valid""" icase, flag0 = self.check_int(self.icase_edit) scale, flag1 = self.check_float(self.scale_edit) time, flag2 = self.check_float(self.time_edit) fps, flag3 = self.check_float(self.fps_edit) animate_in_gui = self.animate_in_gui_checkbox.isChecked() if animate_in_gui: passed = all([flag0, flag1, flag2, flag3]) return passed, (icase, scale, time, fps, animate_in_gui, None, None, None) magnify, flag4 = self.check_int(self.resolution_edit) output_dir, flag5 = self.check_path(self.browse_folder_edit) gifbase, flag6 = self.check_name(self.gif_edit) passed = all([flag0, flag1, flag2, flag3, flag4, flag5, flag6]) return passed, (icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase) @staticmethod def check_name(cell): """verifies that the data is string-able""" cell_value = cell.text() try: text = str(cell_value).strip() except UnicodeEncodeError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False if len(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def check_path(self, cell): """verifies that the path exists""" text, passed = self.check_name(cell) if not passed: return None, False if os.path.exists(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False #def on_ok(self): #"""click the OK button""" #passed = self.on_apply() #if passed: #self.win_parent._animation_window_shown = False #self.close() ##self.destroy() def on_cancel(self): """click the Cancel button""" self.on_stop() self.out_data['close'] = True self.close()
def initSettingTab(self): # ##Setting Tab### setting_tab = QWidget() setting_tab_layout = QVBoxLayout() self.tabWidget.addTab(setting_tab, "Settings") # Task Box task_box = QGroupBox() task_box.setTitle(QString("Task properties")) task_layout = QGridLayout() # Name name = QLabel("Name:") name_value = QLineEdit() name_value.setText(self.task.hittypename) name_value.setEnabled(False) clickable(name_value).connect(self.enable) task_layout.addWidget(name, 0, 1) task_layout.addWidget(name_value, 0, 2, 1, 3) # Description description = QLabel("Description:") description_value = QLineEdit() description_value.setText(self.task.description) description_value.setEnabled(False) clickable(description_value).connect(self.enable) task_layout.addWidget(description, 1, 1) task_layout.addWidget(description_value, 1, 2, 1, 3) # Keywords keywords = QLabel("Keywords:") keywords_value = QLineEdit() keywords_value.setText(','.join(self.task.keywords)) keywords_value.setEnabled(False) clickable(keywords_value).connect(self.enable) task_layout.addWidget(keywords, 2, 1) task_layout.addWidget(keywords_value, 2, 2, 1, 3) # Qualification qualification = QLabel("Qualification [%]:") qualification_value = QSpinBox() qualification_value.setSuffix('%') qualification_value.setValue(int(self.task.qualification)) qualification_value.setEnabled(False) clickable(qualification_value).connect(self.enable) task_layout.addWidget(qualification, 3, 1) task_layout.addWidget(qualification_value, 3, 4) # Assignments assignments = QLabel("Assignments:") assignments_value = QSpinBox() assignments_value.setSuffix('') assignments_value.setValue(int(self.task.assignments)) assignments_value.setEnabled(False) clickable(assignments_value).connect(self.enable) task_layout.addWidget(assignments, 4, 1) task_layout.addWidget(assignments_value, 4, 4) # Duration duration = QLabel("Duration [min]:") duration_value = QSpinBox() duration_value.setSuffix('min') duration_value.setValue(int(self.task.duration)) duration_value.setEnabled(False) clickable(duration_value).connect(self.enable) task_layout.addWidget(duration, 5, 1) task_layout.addWidget(duration_value, 5, 4) # Reward reward = QLabel("Reward [0.01$]:") reward_value = QDoubleSpinBox() reward_value.setRange(0.01, 0.5) reward_value.setSingleStep(0.01) reward_value.setSuffix('$') reward_value.setValue(self.task.reward) reward_value.setEnabled(False) clickable(reward_value).connect(self.enable) task_layout.addWidget(reward, 6, 1) task_layout.addWidget(reward_value, 6, 4) # Lifetime lifetime = QLabel("Lifetime [d]:") lifetime_value = QSpinBox() lifetime_value.setSuffix('d') lifetime_value.setValue(self.task.lifetime) lifetime_value.setEnabled(False) clickable(lifetime_value).connect(self.enable) task_layout.addWidget(lifetime, 7, 1) task_layout.addWidget(lifetime_value, 7, 4) # sandbox sandbox = QCheckBox("Sandbox") sandbox.setChecked(self.task.sandbox) task_layout.addWidget(sandbox, 8, 1) task_box.setLayout(task_layout) task_layout.setColumnMinimumWidth(1, 120) # Image Storage Box storage_box = QGroupBox() storage_box.setTitle(QString("Image Storage")) storage_layout = QGridLayout() # Host URL host_url = QLabel("Host-URL:") host_url_value = QLineEdit() host_url_value.setText(self.task.host_url) host_url_value.setEnabled(False) clickable(host_url_value).connect(self.enable) # Dropbox Path dropbox_path = QLabel("Dropbox-Path:") dropbox_path_value = QLineEdit() dropbox_path_value.setText(self.task.dropbox_path) dropbox_path_value.setEnabled(False) clickable(dropbox_path_value).connect(self.enable) # Dropbox or S3 usingS3 = QRadioButton("S3") usingS3.setChecked(self.task.usingS3) usingS3.setEnabled(False) usingDropbox = QRadioButton("Dropbox") usingDropbox.setChecked(self.task.usingDropbox) storage_layout.addWidget(host_url, 0, 1) storage_layout.addWidget(host_url_value, 0, 2, 1, 3) storage_layout.addWidget(dropbox_path, 1, 1) storage_layout.addWidget(dropbox_path_value, 1, 2, 1, 3) # Add Layouts save_button = QPushButton("Save Settings") setting_tab_layout.addWidget(task_box) setting_tab_layout.addWidget(storage_box) setting_tab.setLayout(setting_tab_layout) save_button.clicked.connect(self.SaveSettings) storage_layout.addWidget(usingS3, 2, 1) storage_layout.addWidget(usingDropbox, 3, 1) storage_layout.addWidget(save_button, 3, 4) # storage_layout.addStretch(1) storage_box.setLayout(storage_layout)
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) label = QLabel() label.setText('The neuron that you will be examining will divide the objects you will show it into the ones\n' + 'that it likes and the ones it dislikes\n' + 'Let\'s assume that be recognized objects are flowers\n') # groupbox1 groupBox1 = QGroupBox() groupBox1.setTitle('Feature weight') groupBox1Label1 = QLabel() groupBox1Label1.setText('Here you enter the neuron\'s weight coefficients for the individual object features. Positve\n' + 'coefficient means approval to the attribute, and negative one will indicate that the given\n' + 'attribute should be disliked by the neuron.') groupBox1Label2 = QLabel() groupBox1Label2.setText('Now, enter if you want the neuron to like the flower that is:') self.spinBoxWeightFragment = QDoubleSpinBox() self.spinBoxWeightFragment.setValue(1.0) self.spinBoxWeightFragment.setRange(-100.0, 100.0) self.spinBoxWeightColorful = QDoubleSpinBox() self.spinBoxWeightColorful.setValue(2.0) self.spinBoxWeightColorful.setRange(-100.0, 100.0) groupBox1HLayout = QHBoxLayout() groupBox1HLayout.addWidget(QLabel('Fragment:')) groupBox1HLayout.addWidget(self.spinBoxWeightFragment) groupBox1HLayout.addWidget(QLabel('Colorful:')) groupBox1HLayout.addWidget(self.spinBoxWeightColorful) groupBox1VLayout = QVBoxLayout() groupBox1VLayout.addWidget(groupBox1Label1) groupBox1VLayout.addWidget(groupBox1Label2) groupBox1VLayout.addLayout(groupBox1HLayout) groupBox1.setLayout(groupBox1VLayout) # groupbox2 groupBox2 = QGroupBox() groupBox2.setTitle('Evaluated object') self.spinBoxObjectFragment = QDoubleSpinBox() self.spinBoxObjectFragment.setRange(-100.0, 100.0) self.spinBoxObjectColorful = QDoubleSpinBox() self.spinBoxObjectColorful.setRange(-100.0, 100.0) groupBox2HLayout = QHBoxLayout() groupBox2HLayout.addWidget(QLabel('Fragment')) groupBox2HLayout.addWidget(self.spinBoxObjectFragment) groupBox2HLayout.addWidget(QLabel('Colorful')) groupBox2HLayout.addWidget(self.spinBoxObjectColorful) groupBox2VLayout = QVBoxLayout() groupBox2VLayout.addWidget(QLabel('After setting the weight, yout can perform experiments. Enter if the flower is:')) groupBox2VLayout.addLayout(groupBox2HLayout) groupBox2.setLayout(groupBox2VLayout) # groupbox3 groupBox3 = QGroupBox() groupBox3.setTitle('Neuron\'s response') pushbuttonGroup3 = QPushButton('Recalculate!') self.output = QLabel() self.attitude = QLabel() groupBox3HLayout1 = QHBoxLayout() groupBox3HLayout1.addWidget(QLabel('The neuron\'s response value is:')) groupBox3HLayout1.addWidget(self.output) groupBox3HLayout2 = QHBoxLayout() groupBox3HLayout2.addWidget(QLabel('It means that the neuron\'s attitude against the flower is:')) groupBox3HLayout2.addWidget(self.attitude) groupBox3HLayout2.addWidget(pushbuttonGroup3) groupBox3VLayout = QVBoxLayout() groupBox3VLayout.addLayout(groupBox3HLayout1) groupBox3VLayout.addLayout(groupBox3HLayout2) groupBox3.setLayout(groupBox3VLayout) layout = QVBoxLayout() layout.addWidget(label) layout.addWidget(groupBox1) layout.addWidget(groupBox2) layout.addWidget(groupBox3) self.setLayout(layout) self.setWindowTitle('Single neuron examination (example 01a)') self.connect(self.spinBoxWeightFragment, SIGNAL('valueChanged(double)'), self.evaluateObject) self.connect(self.spinBoxWeightColorful, SIGNAL('valueChanged(double)'), self.evaluateObject) self.connect(self.spinBoxObjectFragment, SIGNAL('valueChanged(double)'), self.evaluateObject) self.connect(self.spinBoxObjectColorful, SIGNAL('valueChanged(double)'), self.evaluateObject) self.connect(pushbuttonGroup3, SIGNAL('clicked()'), self.evaluateObject) self.neuron = Neuron(2) def evaluateObject(self): self.neuron.weights[0] = self.spinBoxWeightFragment.value() self.neuron.weights[1] = self.spinBoxWeightColorful.value() signals = [self.spinBoxObjectFragment.value(), self.spinBoxObjectColorful.value()] response = self.neuron.response(signals) strength = self.neuron.memoryTraceStrength(Neuron.StrenghtNormManhattan) attitude = '' palette = QPalette() if abs(response) < 0.2 * strength: print 'response ', response, '\t0.2 * strength ', 0.2 * strength, '\tstrenght ', strength, '\tindiffrent' attitude = 'indiffrent' palette.setColor(QPalette.WindowText, Qt.darkCyan) elif response < 0: print 'responce ', response, '\tstrength ', strength, '\tnegative' attitude = 'negative' palette.setColor(QPalette.WindowText, Qt.blue) else: print 'responce ', response, '\tstrength ', strength, '\tpositive' attitude = 'positive' palette.setColor(QPalette.WindowText, Qt.red) self.output.setText(str(response)) self.attitude.setText(attitude) self.attitude.setPalette(palette)
class EditGeometryProperties(PyDialog): force = True def __init__(self, data, win_parent=None): """ +------------------+ | Edit Actor Props | +------------------+------+ | Name1 | | Name2 | | Name3 | | Name4 | | | | Active_Name main | | Color box | | Line_Width 2 | | Point_Size 2 | | Bar_Scale 2 | | Opacity 0.5 | | Show/Hide | | | | Apply OK Cancel | +-------------------------+ """ PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) del self.out_data['font_size'] self.setWindowTitle('Edit Geometry Properties') self.allow_update = True #default #self.win_parent = win_parent #self.out_data = data self.keys = sorted(data.keys()) self.keys = data.keys() keys = self.keys nrows = len(keys) self.active_key = 'main' #keys[0] items = keys header_labels = ['Groups'] table_model = Model(items, header_labels, self) view = CustomQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version == 4: view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table = view actor_obj = data[self.active_key] name = actor_obj.name line_width = actor_obj.line_width point_size = actor_obj.point_size bar_scale = actor_obj.bar_scale opacity = actor_obj.opacity color = actor_obj.color show = actor_obj.is_visible self.representation = actor_obj.representation # table header = self.table.horizontalHeader() header.setStretchLastSection(True) self._default_is_apply = False self.name = QLabel("Name:") self.name_edit = QLineEdit(str(name)) self.name_edit.setDisabled(True) self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data[self.active_key].color qcolor = QtGui.QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QtGui.QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \ #qcolor) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.use_slider = True self.is_opacity_edit_active = False self.is_opacity_edit_slider_active = False self.is_line_width_edit_active = False self.is_line_width_edit_slider_active = False self.is_point_size_edit_active = False self.is_point_size_edit_slider_active = False self.is_bar_scale_edit_active = False self.is_bar_scale_edit_slider_active = False self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) if self.use_slider: self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal) self.opacity_slider_edit.setRange(1, 10) self.opacity_slider_edit.setValue(opacity * 10) self.opacity_slider_edit.setTickInterval(1) self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow) self.line_width = QLabel("Line Width:") self.line_width_edit = QSpinBox(self) self.line_width_edit.setRange(1, 15) self.line_width_edit.setSingleStep(1) self.line_width_edit.setValue(line_width) if self.use_slider: self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal) self.line_width_slider_edit.setRange(1, 15) self.line_width_slider_edit.setValue(line_width) self.line_width_slider_edit.setTickInterval(1) self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation in ['point', 'surface']: self.line_width.setEnabled(False) self.line_width_edit.setEnabled(False) self.line_width_slider_edit.setEnabled(False) self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 15) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) if self.use_slider: self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal) self.point_size_slider_edit.setRange(1, 15) self.point_size_slider_edit.setValue(point_size) self.point_size_slider_edit.setTickInterval(1) self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow) self.point_size_slider_edit.setVisible(False) if self.representation in ['wire', 'surface']: self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.bar_scale = QLabel("Bar Scale:") self.bar_scale_edit = QDoubleSpinBox(self) #self.bar_scale_edit.setRange(0.01, 1.0) # was 0.1 #self.bar_scale_edit.setRange(0.05, 5.0) self.bar_scale_edit.setDecimals(1) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) self.bar_scale_edit.setSingleStep(0.1) self.bar_scale_edit.setValue(bar_scale) #if self.use_slider: #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal) #self.bar_scale_slider_edit.setRange(1, 100) # 1/0.05 = 100/5.0 #self.bar_scale_slider_edit.setValue(opacity * 0.05) #self.bar_scale_slider_edit.setTickInterval(10) #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation != 'bar': self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setEnabled(False) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.cancel_button = QPushButton("Close") self.create_layout() self.set_connections() def on_update_geometry_properties_window(self, data): """Not Implemented""" return #new_keys = sorted(data.keys()) #if self.active_key in new_keys: #i = new_keys.index(self.active_key) #else: #i = 0 #self.table.update_data(new_keys) #self.out_data = data #self.update_active_key(i) def update_active_key(self, index): """ Parameters ---------- index : PyQt4.QtCore.QModelIndex the index of the list Internal Parameters ------------------- name : str the name of obj obj : CoordProperties, AltGeometry the storage object for things like line_width, point_size, etc. """ if qt_version == 4: name = str(index.data().toString()) else: name = str(index.data()) print('name = %r' % name) #i = self.keys.index(self.active_key) self.active_key = name self.name_edit.setText(name) obj = self.out_data[name] if isinstance(obj, CoordProperties): opacity = 1.0 representation = 'coord' is_visible = obj.is_visible elif isinstance(obj, AltGeometry): line_width = obj.line_width point_size = obj.point_size bar_scale = obj.bar_scale opacity = obj.opacity representation = obj.representation is_visible = obj.is_visible self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.allow_update = False self.force = False self.line_width_edit.setValue(line_width) self.point_size_edit.setValue(point_size) self.bar_scale_edit.setValue(bar_scale) self.force = True self.allow_update = True else: raise NotImplementedError(obj) allowed_representations = [ 'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar' ] if self.representation != representation: self.representation = representation if representation not in allowed_representations: msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % ( name, representation, allowed_representations) if self.representation == 'coord': self.color.setVisible(False) self.color_edit.setVisible(False) self.line_width.setVisible(False) self.line_width_edit.setVisible(False) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) self.opacity.setVisible(False) self.opacity_edit.setVisible(False) if self.use_slider: self.opacity_slider_edit.setVisible(False) self.point_size_slider_edit.setVisible(False) self.line_width_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setVisible(True) self.color_edit.setVisible(True) self.line_width.setVisible(True) self.line_width_edit.setVisible(True) self.point_size.setVisible(True) self.point_size_edit.setVisible(True) self.bar_scale.setVisible(True) #self.bar_scale_edit.setVisible(True) self.opacity.setVisible(True) self.opacity_edit.setVisible(True) if self.use_slider: self.opacity_slider_edit.setVisible(True) self.line_width_slider_edit.setVisible(True) self.point_size_slider_edit.setVisible(True) #self.bar_scale_slider_edit.setVisible(True) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) self.line_width.setEnabled(True) self.line_width_edit.setEnabled(True) self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) show_points = False show_line_width = True show_bar_scale = False if self.use_slider: self.line_width_slider_edit.setEnabled(True) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setEnabled(True) self.color_edit.setEnabled(True) show_points = False if self.representation in ['point', 'wire+point']: show_points = True show_line_width = False if self.representation in ['wire', 'wire+point', 'bar']: show_line_width = True if representation == 'bar': show_bar_scale = True else: show_bar_scale = False #self.bar_scale_button.setVisible(show_bar_scale) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) #if self.use_slider: #self.bar_scale_slider_edit.setEnabled(False) self.point_size.setEnabled(show_points) self.point_size_edit.setEnabled(show_points) self.point_size.setVisible(show_points) self.point_size_edit.setVisible(show_points) self.line_width.setEnabled(show_line_width) self.line_width_edit.setEnabled(show_line_width) self.bar_scale.setEnabled(show_bar_scale) self.bar_scale_edit.setEnabled(show_bar_scale) self.bar_scale.setVisible(show_bar_scale) self.bar_scale_edit.setVisible(show_bar_scale) if self.use_slider: self.point_size_slider_edit.setEnabled(show_points) self.point_size_slider_edit.setVisible(show_points) self.line_width_slider_edit.setEnabled(show_line_width) #if self.representation in ['wire', 'surface']: self.opacity_edit.setValue(opacity) #if self.use_slider: #self.opacity_slider_edit.setValue(opacity*10) self.checkbox_show.setChecked(is_visible) self.checkbox_hide.setChecked(not is_visible) passed = self.on_validate() #self.on_apply(force=True) # TODO: was turned on...do I want this??? #self.allow_update = True #def on_name_select(self): #print('on_name_select') #return def create_layout(self): ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) grid = QGridLayout() irow = 0 grid.addWidget(self.name, irow, 0) grid.addWidget(self.name_edit, irow, 1) irow += 1 grid.addWidget(self.color, irow, 0) grid.addWidget(self.color_edit, irow, 1) irow += 1 grid.addWidget(self.opacity, irow, 0) if self.use_slider: grid.addWidget(self.opacity_edit, irow, 2) grid.addWidget(self.opacity_slider_edit, irow, 1) else: grid.addWidget(self.opacity_edit, irow, 1) irow += 1 grid.addWidget(self.line_width, irow, 0) if self.use_slider: grid.addWidget(self.line_width_edit, irow, 2) grid.addWidget(self.line_width_slider_edit, irow, 1) else: grid.addWidget(self.line_width_edit, irow, 1) irow += 1 grid.addWidget(self.point_size, irow, 0) if self.use_slider: grid.addWidget(self.point_size_edit, irow, 2) grid.addWidget(self.point_size_slider_edit, irow, 1) else: grid.addWidget(self.point_size_edit, irow, 1) irow += 1 grid.addWidget(self.bar_scale, irow, 0) if self.use_slider and 0: grid.addWidget(self.bar_scale_edit, irow, 2) grid.addWidget(self.bar_scale_slider_edit, irow, 1) else: grid.addWidget(self.bar_scale_edit, irow, 1) irow += 1 checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(grid) if 0: vbox.addWidget(self.checkbox_show) vbox.addWidget(self.checkbox_hide) else: vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) vbox.addLayout(vbox1) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): self.opacity_edit.valueChanged.connect(self.on_opacity) self.line_width_edit.valueChanged.connect(self.on_line_width) self.point_size_edit.valueChanged.connect(self.on_point_size) self.bar_scale_edit.valueChanged.connect(self.on_bar_scale) if self.use_slider: self.opacity_slider_edit.valueChanged.connect( self.on_opacity_slider) self.line_width_slider_edit.valueChanged.connect( self.on_line_width_slider) self.point_size_slider_edit.valueChanged.connect( self.on_point_size_slider) #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider) # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) if qt_version == 4: self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) self.color_edit.clicked.connect(self.on_color) self.checkbox_show.clicked.connect(self.on_show) self.checkbox_hide.clicked.connect(self.on_hide) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.on_cancel() def on_color(self): """called when the user clicks on the color box""" name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color_float = col.getRgbF()[:3] obj.color = color_float color_int = [int(colori * 255) for colori in color_float] self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color_int) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) #print(self.allow_update) def on_show(self): """shows the actor""" name = self.active_key is_checked = self.checkbox_show.isChecked() self.out_data[name].is_visible = is_checked self.on_apply(force=self.force) def on_hide(self): """hides the actor""" name = self.active_key is_checked = self.checkbox_hide.isChecked() self.out_data[name].is_visible = not is_checked self.on_apply(force=self.force) def on_line_width(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_active = True name = self.active_key line_width = self.line_width_edit.value() self.out_data[name].line_width = line_width if not self.is_line_width_edit_slider_active: if self.use_slider: self.line_width_slider_edit.setValue(line_width) self.is_line_width_edit_active = False self.on_apply(force=self.force) self.is_line_width_edit_active = False def on_line_width_slider(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_slider_active = True #name = self.active_key line_width = self.line_width_slider_edit.value() if not self.is_line_width_edit_active: self.line_width_edit.setValue(line_width) self.is_line_width_edit_slider_active = False def on_point_size(self): """increases/decreases the point size""" self.is_point_size_edit_active = True name = self.active_key point_size = self.point_size_edit.value() self.out_data[name].point_size = point_size if not self.is_point_size_edit_slider_active: if self.use_slider: self.point_size_slider_edit.setValue(point_size) self.is_point_size_edit_active = False self.on_apply(force=self.force) self.is_point_size_edit_active = False def on_point_size_slider(self): """increases/decreases the point size""" self.is_point_size_edit_slider_active = True name = self.active_key point_size = self.point_size_slider_edit.value() if not self.is_point_size_edit_active: self.point_size_edit.setValue(point_size) self.is_point_size_edit_slider_active = False def on_bar_scale(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_active = True name = self.active_key float_bar_scale = self.bar_scale_edit.value() self.out_data[name].bar_scale = float_bar_scale if not self.is_bar_scale_edit_slider_active: int_bar_scale = int(round(float_bar_scale * 20, 0)) #if self.use_slider: #self.bar_scale_slider_edit.setValue(int_bar_scale) self.is_bar_scale_edit_active = False self.on_apply(force=self.force) self.is_bar_scale_edit_active = False def on_bar_scale_slider(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_slider_active = True name = self.active_key int_bar_scale = self.bar_scale_slider_edit.value() if not self.is_bar_scale_edit_active: float_bar_scale = int_bar_scale / 20. self.bar_scale_edit.setValue(float_bar_scale) self.is_bar_scale_edit_slider_active = False def on_opacity(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_active = True name = self.active_key float_opacity = self.opacity_edit.value() self.out_data[name].opacity = float_opacity if not self.is_opacity_edit_slider_active: int_opacity = int(round(float_opacity * 10, 0)) if self.use_slider: self.opacity_slider_edit.setValue(int_opacity) self.is_opacity_edit_active = False self.on_apply(force=self.force) self.is_opacity_edit_active = False def on_opacity_slider(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_slider_active = True name = self.active_key int_opacity = self.opacity_slider_edit.value() if not self.is_opacity_edit_active: float_opacity = int_opacity / 10. self.opacity_edit.setValue(float_opacity) self.is_opacity_edit_slider_active = False #def on_axis(self, text): ##print(self.combo_axis.itemText()) #self._axis = str(text) #self.plane.setText('Point on %s? Plane:' % self._axis) #self.point_a.setText('Point on %s Axis:' % self._axis) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def on_plane(self, text): #self._plane = str(text) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def _on_float(self, field): #try: #eval_float_from_string(field.text()) #field.setStyleSheet("QLineEdit{background: white;}") #except ValueError: #field.setStyleSheet("QLineEdit{background: red;}") #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() #old_obj.color = self.color_edit old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self, force=False): passed = self.on_validate() #print("passed=%s force=%s allow=%s" % (passed, force, self.allow_update)) if (passed or force) and self.allow_update and hasattr( self.win_parent, 'on_update_geometry_properties'): #print('obj = %s' % self.out_data[self.active_key]) self.win_parent.on_update_geometry_properties(self.out_data, name=self.active_key) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) groupBox1 = QGroupBox() groupBox1.setTitle('Feature weights (model object)') self.w1 = QDoubleSpinBox() self.w1.setRange(-10.0, 10.0) self.w1.setValue(5.0) self.w2 = QDoubleSpinBox() self.w2.setRange(-10.0, 10.0) self.w2.setValue(5.0) buttonHelpGroupBox1 = QPushButton('help') buttonHelpGroupBox1.setToolTip('Here you enter the neuron\'s weight coefficients for the individual object features.\n' + 'Positive coefficient means approval to the feature, and negative one will indicate that\n' + 'the given feature should be disliked by the neuron.\n\n' + 'Now the only important thing will be the numeric values of the weights and input signals.\n' + 'However, if you want, you can still imagine that the examined objects are flowers - as\n' + 'in the previous program. The w(1) weight will then indicate the fragrance intensity of\n' + 'the flower, and the w(2) weight - its colour intensity.\n\n' + 'You can also think about this as the location of the "model object".') buttonHelpGroupBox1.setEnabled(False) hBoxLayoutGroupBox1 = QHBoxLayout() hBoxLayoutGroupBox1.addWidget(QLabel('w(1) = ')) hBoxLayoutGroupBox1.addWidget(self.w1) hBoxLayoutGroupBox1.addWidget(QLabel('w(2) = ')) hBoxLayoutGroupBox1.addWidget(self.w2) hBoxLayoutGroupBox1.addWidget(buttonHelpGroupBox1) groupBox1.setLayout(hBoxLayoutGroupBox1) groupBox2 = QGroupBox() groupBox2.setTitle('Evaluated object') self.x1 = QDoubleSpinBox() self.x1.setRange(-10.0, 10.0) self.x1.setValue(-5.0) self.x2 = QDoubleSpinBox() self.x2.setRange(-10.0, 10.0) self.x2.setValue(-5.0) buttonHelpGroupBox2 = QPushButton('help') buttonHelpGroupBox2.setToolTip('Here you can enter the feature values of the evaluated object. As above, you are\n' + 'free to imagine that it is a flower whose fragrance intensity is x(1) and colour intensity\n' + 'is x(2).a') buttonHelpGroupBox2.setEnabled(False) hBoxLayoutGroupBox2 = QHBoxLayout() hBoxLayoutGroupBox2.addWidget(QLabel('x(1) = ')) hBoxLayoutGroupBox2.addWidget(self.x1) hBoxLayoutGroupBox2.addWidget(QLabel('x(2) = ')) hBoxLayoutGroupBox2.addWidget(self.x2) hBoxLayoutGroupBox2.addWidget(buttonHelpGroupBox2) groupBox2.setLayout(hBoxLayoutGroupBox2) groupBox3 = QGroupBox() groupBox3.setTitle('Graph') self.colorResponse = QLabel('Evaluated object') buttonHelpGroupBox3 = QPushButton('help') buttonHelpGroupBox3.setToolTip('On your left, you see a signal graph. The blue point represents the location of the\n' + 'model object. The other point is the location of the evaluated object. Its color, shown\n' + 'on the chart\'s key, corresponds to the neuron\'s attitude towards the evaluated\n' + 'object.\n\n' + 'Click the graph with the right mouse button to set the model object location. The left\n' + 'mouse button sets the evaluated object. You can also perform dragging to move the\n' + 'objects smoothly.') buttonHelpGroupBox3.setEnabled(False) hBoxLayoutGroupBox3 = QHBoxLayout() hBoxLayoutGroupBox3.addWidget(self.colorResponse) hBoxLayoutGroupBox3.addWidget(buttonHelpGroupBox3) vBoxLayoutGroupBox3 = QVBoxLayout() vBoxLayoutGroupBox3.addWidget(QLabel('Key')) vBoxLayoutGroupBox3.addWidget(QLabel('Model object')) vBoxLayoutGroupBox3.addLayout(hBoxLayoutGroupBox3) groupBox3.setLayout(vBoxLayoutGroupBox3) self.response = QLabel('0') hBoxLayoutResponse = QHBoxLayout() hBoxLayoutResponse.addWidget(QLabel('Neuron\'s response: ')) hBoxLayoutResponse.addWidget(self.response) vBoxlayout = QVBoxLayout() vBoxlayout.addWidget(QLabel('The neuron that you will be examining will divide the objects you\n' + 'will show it into the ones that it likes and the ones id dislikes.')) vBoxlayout.addWidget(groupBox1) vBoxlayout.addWidget(groupBox2) vBoxlayout.addLayout(hBoxLayoutResponse) vBoxlayout.addWidget(groupBox3) self.figure = plot.figure() self.canvas = FigureCanvas(self.figure) self.customePlot() hBoxLayout = QHBoxLayout() hBoxLayout.addWidget(self.canvas) hBoxLayout.addLayout(vBoxlayout) self.neuron = Neuron(2) self.evaluatedObject() self.setLayout(hBoxLayout) self.setWindowTitle('Single neuron examination with visualization (example 01b)') self.connect(self.w1, SIGNAL('valueChanged(double)'), self.evaluatedObject) self.connect(self.w2, SIGNAL('valueChanged(double)'), self.evaluatedObject) self.connect(self.x1, SIGNAL('valueChanged(double)'), self.evaluatedObject) self.connect(self.x2, SIGNAL('valueChanged(double)'), self.evaluatedObject) def evaluatedObject(self): self.figure.clear() self.customePlot() ax = self.figure.add_subplot(111) valueW1 = self.w1.value() valueW2 = self.w2.value() self.neuron.weights[0] = valueW1 self.neuron.weights[1] = valueW2 plot.scatter(valueW1, valueW2, color='k') plot.plot([0.0, valueW1],[0.0, valueW2], color='k') plot.plot([0.0, valueW1], [valueW2, valueW2], 'r--', linewidth=2) plot.plot([valueW1, valueW1], [0.0, valueW2], 'r--', linewidth=2) valueX1 = self.x1.value() valueX2 = self.x2.value() inputs = [valueX1, valueX2] response = self.neuron.response(inputs) strength = self.neuron.memoryTraceStrength(Neuron.StrenghtNormEuclidean) palette = QPalette() if abs(response) < 0.2 * strength: palette.setColor(QPalette.WindowText, Qt.darkCyan) elif response < 0: palette.setColor(QPalette.WindowText, Qt.blue) else: palette.setColor(QPalette.WindowText, Qt.red) self.colorResponse.setPalette(palette) self.response.setPalette(palette) self.response.setText(str(response)) plot.scatter(valueX1, valueX2, color='k') plot.plot([0.0, valueX1],[0.0, valueX2], color='k') plot.plot([0.0, valueX1], [valueX2, valueX2], 'b--', linewidth=2) plot.plot([valueX1, valueX1], [0.0, valueX2], 'b--', linewidth=2) self.canvas.draw() def customePlot(self): plot.xlim(-10.0, 10.0) plot.ylim(-10.0, 10.0) ax = plot.subplot() ax.grid(True, which='both') # y axis ax.spines['bottom'].set_position('center') # x axis ax.spines['left'].set_position('center')
class ItemTreeWidget(GenericTreeWidget): def __init__(self, session, parent, creator): GenericTreeWidget.__init__(self, session, parent) self.creator = creator self.setTitle('Tuotteet') self.setButtons([ButtonType.add, ButtonType.open, ButtonType.remove]) self.setHeader(headertexts=['id', 'Nimi', 'Tyyppi', 'Hinta', 'Määrä'], hidecolumns=[0]) from mainwindowtabs.itemcreatordialog import ItemCreatorDialog self.setInputMethod(tabcreator=ItemCreatorDialog, autoAdd=True, function=SqlHandler.searchItem) self.countSpinBox = QDoubleSpinBox(parent=self) self.countSpinBox.setRange(0.01, 99999999) self.countSpinBox.setValue(1) if self.ui.topLayout.count() > 0 or self.ui.bottomLayout.count() == 0: self.ui.topLayout.insertWidget(self.ui.topLayout.count(), self.countSpinBox) else: self.ui.bottomLayout.incertWidget(self.ui.bottomLayout.count(), self.countSpinBox) self.setUpTreewidget() self.countSpinBox.valueChanged['double'].connect(self.updateItemCount) self.ui.treeWidget.currentItemChanged.connect(self.handleChange) def setUpTreewidget(self): if self.ui.treeWidget.currentItem() != None: #set item count to countSpinBox self.countSpinBox.setValue(self.ui.treeWidget.currentItem().data( 0, 0).count) def updateItemCount(self, count): current = self.ui.treeWidget.currentItem() if current.data(0, 0).count != count: current.data(0, 0).count = count current.setText(3, '%.2f' % (current.data(0, 0).item.price * count)) current.setText(4, str(count)) def handleChange(self, current, previous): if current != None: self.countSpinBox.setValue(self.ui.treeWidget.currentItem().data( 0, 0).count) ''' This function is called when: 1. searchLineEdit returns new item (Item) 2. list of items is loaded from Surgery or SurgeryBase object 3. just wanted to increase count of current item. item is type of Item/SurgeryItem/SurgetyBaseItem ''' def addItemToTree(self, item): if item != None: if self.creator and item.getType() == self.creator.getType(): #Now we are loading data from Surgery or Surgery base object #So we make new tree objects and add counts to them treeItem = self.makeTreeItem(item) self.ui.treeWidget.addTopLevelItem(treeItem) self.ui.treeWidget.setCurrentItem(treeItem) else: item_index = self.itemInList(item) if item_index < 1: #Item isnt found from list so we make new treeItem = self.makeTreeItem(item) self.ui.treeWidget.addTopLevelItem(treeItem) self.ui.treeWidget.setCurrentItem(treeItem) else: #item is in list and it is just returned from Itemcreator and data is needed to be edited #or it it is tryed to add by searchline edit removedItem = self.ui.treeWidget.takeTopLevelItem( item_index) #take line from list item_data = item.stringList() #get item new string list #update data, only item data not for i in range(1, len(item_data)): removedItem.setText( i, item_data[i]) #set updated text to line self.ui.treeWidget.addTopLevelItem( removedItem) #add line back to list self.ui.treeWidget.setCurrentItem( removedItem) #set it current item def getItemsFromList(self): itemList = [] for i in range(0, self.ui.treeWidget.topLevelItemCount()): itemList.append(self.ui.treeWidget.topLevelItem(i).data(0, 0)) return itemList def removeSelectedItem(self): temp = self.ui.treeWidget.currentItem() if temp != None: removedItem = self.ui.treeWidget.takeTopLevelItem( self.ui.treeWidget.indexOfTopLevelItem(temp)) if removedItem != None: item = removedItem.data(0, 0) if item in self.session: self.session.delete(item) def openItem(self): tree_item = self.ui.treeWidget.currentItem() if tree_item != None: creator = self.tabcreator(parent=self, item=tree_item.data(0, 0).item) creator.show() ''' item is Item(any of them) or SurgeryItem/SurgeryBaseItem if creator is None it means that we should add item as it is ''' def makeTreeItem(self, item): if self.creator and item.getType() != self.creator.getType(): item = self.creator(item) #make new item textString = item.stringList() #has all info treeItem = QTreeWidgetItem(self.ui.treeWidget, textString) treeItem.setData(0, 0, item) return treeItem def itemInList(self, item): if self.creator and item.getType() == self.creator.getType( ): #get item from SurgeryBaseItem/SurgeryItem item = item.item for i in range(0, self.ui.treeWidget.topLevelItemCount()): temp_item = self.ui.treeWidget.topLevelItem(i).data(0, 0) if temp_item.item.id == item.id: return i #item not found return -1
def __init__(self, parent=None): super(Widget, self).__init__(parent) buttonHelp1 = QPushButton('help') buttonHelp1.setEnabled(False) buttonHelp1.setToolTip('The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') buttonHelp2 = QPushButton('help') buttonHelp2.setEnabled(False) buttonHelp2.setToolTip('If you show the winner, you will see the neuron whose response was the strongest.\n' + 'This neuron indicates the animal class the examined object will most probably fall into.\n' + 'The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') hBoxLayout1 = QHBoxLayout() hBoxLayout1.addWidget(QLabel('The neural network in this example uses five features to recognize\n' + 'three classes of animals. Its weight coefficients are predefined and shown in the table below.\n\n' + 'To test the network behavior, enter the input signals in the rightmost column and read the output\n' + 'values from the bottom row.')) hBoxLayout1.addWidget(buttonHelp1) self.checkBoxWinner = QCheckBox() self.checkBoxWinner.setText('Show the winner') hBoxLayout2 = QHBoxLayout() hBoxLayout2.addWidget(self.checkBoxWinner) hBoxLayout2.addWidget(buttonHelp2) self.tableWidget = QTableWidget() self.labelNeuron = QLabel('(There is no winner.)') self.labelType = QLabel('This is something strange!') self.spinBoxThreshold = QDoubleSpinBox() self.spinBoxThreshold.setValue(5.0) self.groupBox = QGroupBox('Show the winner') gridLayout = QGridLayout() gridLayout.addWidget(QLabel('And the winner is...'), 0, 0) gridLayout.addWidget(self.labelNeuron, 0, 1) gridLayout.addWidget(QLabel('Because of this, the network claims:'), 1, 0) gridLayout.addWidget(self.labelType, 1, 1) gridLayout.addWidget(QLabel('Threshold:'), 2, 0) gridLayout.addWidget(self.spinBoxThreshold, 2, 1) self.groupBox.setLayout(gridLayout) self.groupBox.setVisible(False) vBoxLayout = QVBoxLayout() vBoxLayout.addLayout(hBoxLayout1) vBoxLayout.addWidget(self.tableWidget) vBoxLayout.addLayout(hBoxLayout2) vBoxLayout.addWidget(self.groupBox) self.setLayout(vBoxLayout) self.setWindowTitle('Simple linear neural network (example2)') self.classNames = ['mammal', 'bird', 'fish'] self.tableWidget.setColumnCount(5) self.tableWidget.setRowCount(6) self.tableWidget.verticalHeader().hide() self.tableWidget.setHorizontalHeaderLabels(['Feature'] + self.classNames + ['Input vector']) self.tableWidget.setCellWidget(0, 0, QLabel('number of legs')) self.tableWidget.setCellWidget(1, 0, QLabel('lives in water')) self.tableWidget.setCellWidget(2, 0, QLabel('can fly')) self.tableWidget.setCellWidget(3, 0, QLabel('has feathers')) self.tableWidget.setCellWidget(4, 0, QLabel('egg-laying')) self.tableWidget.setCellWidget(5, 0, QLabel('Output')) weights = [ [ 4, 0.01, 0.01, -1, -1.5 ], [ 2, -1, 2, 2.5, 2 ], [ -1, 3.5, 0.01, -2, 1.5 ] ] for i in xrange(len(weights)): for j in xrange(len(weights[i])): self.tableWidget.setCellWidget(j, i + 1, QLabel(' ' + str(weights[i][j]))) for i in xrange(len(weights)): self.tableWidget.setCellWidget(5, i + 1, QLabel('')) for i in xrange(len(weights[0])): doubleSpinBox = QDoubleSpinBox() doubleSpinBox.setValue(0.0) doubleSpinBox.setRange(-15.0, 15.0) self.tableWidget.setCellWidget(i, 4, doubleSpinBox) self.tableWidget.setCellWidget(5, 4, QPushButton('Calculate')) self.linearNetwork = LinearNetwork(initialWeights=weights) self.connect(self.checkBoxWinner, SIGNAL('stateChanged(int)'), self.visibleGrid) self.connect(self.tableWidget.cellWidget(5, 4), SIGNAL('clicked()'), self.updateResult) self.resize(600, 400)
class dbsMiscControlsDialog(QDialog): def __init__(self, callback, parent=None): QDialog.__init__(self, parent) self.callback = callback self.create_widgets() self.layout_widgets() self.create_connections() self.setModal(False) self.setWindowTitle('Misc. Controls') def create_widgets(self): self.op_pick_label = QLabel('Picking Opacity Isoval') self.op_pick_sbox = QDoubleSpinBox() self.op_pick_sbox.setRange(0, 1.0) self.op_pick_sbox.setSingleStep(0.02) self.op_pick_sbox.setValue(0.5) self.vta_combox_label = QLabel('Statistic') self.vta_stats_combox = QComboBox() self.vta_stats_combox.insertItem(0, 'Mean') self.vta_stats_combox.insertItem(1, 'Var') self.vta_stats_combox.insertItem(2, 'Min') self.vta_stats_combox.insertItem(3, 'Max') self.vta_stats_combox.insertItem(4, 'Mean-Var') self.vta_stats_combox.insertItem(5, 'Min-Var') self.vta_stats_combox.insertItem(6, 'Max-Var') self.vta_stats_combox.insertItem(7, 'NumSamples') self.__setupWidgetsForClippingPlanes() def layout_widgets(self): misc_controls_gl = QGridLayout() misc_controls_gl.addWidget(self.vta_combox_label, 0, 0) misc_controls_gl.addWidget(self.vta_stats_combox, 0, 1) misc_controls_gl.addWidget(self.op_pick_label, 1, 0) misc_controls_gl.addWidget(self.op_pick_sbox, 1, 1) misc_controls_gl.addWidget(self.cpl_xmax_label, 2, 0) misc_controls_gl.addWidget(self.cpl_xmax, 2, 1) misc_controls_gl.addWidget(self.cpl_ymax_label, 3, 0) misc_controls_gl.addWidget(self.cpl_ymax, 3, 1) misc_controls_gl.addWidget(self.cpl_zmax_label, 4, 0) misc_controls_gl.addWidget(self.cpl_zmax, 4, 1) self.setLayout(misc_controls_gl) self.layout().setSizeConstraint( QLayout.SetFixedSize ) def create_connections(self): self.op_pick_sbox.valueChanged.connect(self.__setVolOpacityForPicking) self.cpl_ymax.valueChanged.connect(self.__setClippingPlaneYmax) self.cpl_xmax.valueChanged.connect(self.__setClippingPlaneXmax) self.cpl_zmax.valueChanged.connect(self.__setClippingPlaneZmax) self.vta_stats_combox.currentIndexChanged.connect(self.__setVolToRender) def getStatComboBoxIndex(self, stat): ''' Returns index of statistic. ''' if stat == 'Mean': return 0 elif stat == 'Var': return 1 elif stat == 'Min': return 2 elif stat == 'Max': return 3 elif stat == 'Mean-Var': return 4 elif stat == 'Min-Var': return 5 elif stat == 'Max-Var': return 6 elif stat == 'NumSamples': return 6 def updateWidgetValues(self): ''' Allows application to set values on widget controls. ''' par = self.parent() actv = self.parent().active_vol self.cpl_xmax.setValue(par._vdata[actv].volumeClipXmax.GetOrigin()[0]) self.cpl_ymax.setValue(par._vdata[actv].volumeClipYmax.GetOrigin()[1]) self.cpl_zmax.setValue(par._vdata[actv].volumeClipXmax.GetOrigin()[2]) self.op_pick_sbox.setValue(par._vdata[actv].picking_opacity) stat = QString(par._vdata[actv].curr_statistic) idx = self.getStatComboBoxIndex(stat) self.vta_stats_combox.setCurrentIndex(idx) def __setupWidgetsForClippingPlanes(self): self.cpl_xmax_label = QLabel( 'Clipping Plane X' ) self.cpl_xmax = QSlider(Qt.Horizontal) self.cpl_xmax.setRange(-30.000000, -30 + 120 * 0.252) # data set dependent # todo - set this with loadable dimensions config file with data self.cpl_ymax_label = QLabel( 'Clipping Plane Y' ) self.cpl_ymax = QSlider(Qt.Horizontal) self.cpl_ymax.setRange(-15.000000, -15 + 120 * 0.252) self.cpl_zmax_label = QLabel( 'Clipping Plane Z' ) self.cpl_zmax = QSlider(Qt.Horizontal) self.cpl_zmax.setRange(-30.000000, -30 + 120 * 0.252) def __setVolOpacityForPicking(self): op = self.op_pick_sbox.value() av = self.parent().active_vol self.parent()._vdata[av].picking_opacity = op self.parent()._picker.SetVolumeOpacityIsovalue(op) def __setClippingPlaneYmax(self): av = self.parent().active_vol self.parent()._vdata[av].yclip = self.cpl_ymax.value() self.parent()._vdata[av].volumeClipYmax.SetOrigin(-30, self.cpl_ymax.value(), -30) self.apply() def __setClippingPlaneXmax(self): av = self.parent().active_vol self.parent()._vdata[av].xclip = self.cpl_xmax.value() self.parent()._vdata[av].volumeClipXmax.SetOrigin(self.cpl_xmax.value(), -10, -30) self.apply() def __setClippingPlaneZmax(self): av = self.parent().active_vol self.parent()._vdata[av].zclip = self.cpl_zmax.value() self.parent()._vdata[av].volumeClipZmax.SetOrigin(-30, -10, self.cpl_zmax.value()) self.apply() def __setVolToRender(self): par = self.parent() stat = self.vta_stats_combox.currentText() av = par.active_vol vol_to_renderer = str(stat) par._vdata[av].curr_statistic = vol_to_renderer par._vdata[av].assignVolumeProperties() par._colorControlsDialog.setTFChart( par._vdata[av].chart ) self.__setClippingPlaneXmax() self.__setClippingPlaneYmax() self.__setClippingPlaneZmax() self.apply() def apply(self): av = self.parent().active_vol self.parent().vol_qvtk_widgets[av].update()