def createVulnOptions(self): """ Vulnerability Discovery related """ groupBox = QtGui.QGroupBox('Vulnerability Discovery') # Elements cbv_deep_dang = QCheckBox('Deep search for dangerous functions') # xxx = QCheckBox('blah') # Default states are read from the Options # class and reflected in the GUI cbv_deep_dang.setCheckState(self.get_state(self.config.deep_dangerous_functions)) # Connect elements and signals cbv_deep_dang.stateChanged.connect(self.deep_dangerous) vbox = QtGui.QVBoxLayout() vbox.addWidget(cbv_deep_dang) # vbox.addWidget(xxx) vbox.addStretch(1) groupBox.setLayout(vbox) return groupBox
def createEditor(self, parent, option, index): if not index.isValid(): return QSqlRelationalDelegate.createEditor(self, parent, option, index) if index.column() in self.__read_only: return None elif index.column() in self.__dates: return QDateEdit(QDate.currentDate(), parent) elif index.column() in self.__booleens: editor = QCheckBox("", parent) r = self.checkBoxRect(option, editor) rect = option.rect rect.moveTo(r.x(), r.y()) rect.setWidth(r.width()) rect.setHeight(r.height()) editor.setGeometry(rect) editor.setAutoFillBackground(True) return editor elif index.column() in self.__numbers: editor = QSpinBox(parent) editor.setMinimum(0) editor.setMaximum(100) return editor return QSqlRelationalDelegate.createEditor(self, parent, option, index)
def __init__(self, group_name, name_list, param_type = int, default_param = None, help_instance = None, handler = None, help_dict = None): QGroupBox.__init__(self, group_name) the_layout = QVBoxLayout() the_layout.setSpacing(5) the_layout.setContentsMargins(1, 1, 1, 1) self.setLayout(the_layout) self.widget_dict = OrderedDict([]) self.mytype= param_type self.is_popup = False if default_param == None: default_param = "" self.default_param = default_param for txt in name_list: qh = QHBoxLayout() cb = QCheckBox(txt) cb.setFont(QFont('SansSerif', 12)) efield = QLineEdit(str(default_param)) efield.setFont(QFont('SansSerif', 10)) efield.setMaximumWidth(25) qh.addWidget(cb) qh.addStretch() qh.addWidget(efield) the_layout.addLayout(qh) if handler != None: cb.toggled.connect(handler) self.widget_dict[txt] = [cb, efield] if (help_dict != None) and (help_instance != None): if txt in help_dict: help_button_widget = help_instance.create_button(txt, help_dict[txt]) qh.addWidget(help_button_widget) return
def buildAttributeGroupBox(self): """Layout/construct the AttributeScene UI for this tab.""" groupBox = QGroupBox("Attribute Policy (Colors)") layout = QVBoxLayout() # agent.propagate_attribute_scenes self.attr_propagate = QCheckBox( "Propagate attribute scene " + "information (e.g. color maps) to other modules." ) self.attr_propagate.setChecked(self.agent.propagate_attribute_scenes) self.attr_propagate.stateChanged.connect(self.attrPropagateChanged) # We only allow this change if the parent does not propagate if self.agent.parent().propagate_attribute_scenes: self.attr_propagate.setDisabled(True) # agent.apply_attribute_scenes self.attr_applyScene = QCheckBox("Apply attribute scene information " + "from other modules.") self.attr_applyScene.setChecked(self.agent.apply_attribute_scenes) self.attr_applyScene.stateChanged.connect(self.attrApplyChanged) layout.addWidget(self.attr_applyScene) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.attr_propagate) groupBox.setLayout(layout) return groupBox
def __init__(self, group_name, name_list, param_dict, help_instance = None, handler = None, help_dict = None): QGroupBox.__init__(self, group_name) the_layout = QVBoxLayout() the_layout.setSpacing(5) the_layout.setContentsMargins(1, 1, 1, 1) self.setLayout(the_layout) self.widget_dict = {} self.is_popup = False self.param_dict = param_dict for txt in name_list: qh = QHBoxLayout() cb = QCheckBox(txt) qh.addWidget(cb) cb.setFont(QFont('SansSerif', 12)) param_widgets = {} for key, val in param_dict.items(): if type(val) == list: # param_widgets[key] = qHotField(key, type(val[0]), val[0], value_list=val, pos="top") else: param_widgets[key] = qHotField(key, type(val), val, pos="top") qh.addWidget(param_widgets[key]) qh.addStretch() the_layout.addLayout(qh) if handler != None: cb.toggled.connect(handler) self.widget_dict[txt] = [cb, param_widgets] if (help_dict != None) and (help_instance != None): if txt in help_dict: help_button_widget = help_instance.create_button(txt, help_dict[txt]) qh.addWidget(help_button_widget) return
def __init__(self, *args, **kwargs ): QWidget.__init__( self, *args, **kwargs ) mainLayout = QHBoxLayout( self ) mainLayout.setContentsMargins(0,0,0,0) label = QLabel( "Aim Direction : " ) lineEdit1 = QLineEdit() lineEdit2 = QLineEdit() lineEdit3 = QLineEdit() verticalSeparator = Widget_verticalSeparator() checkBox = QCheckBox( "Set Auto" ) mainLayout.addWidget( label ) mainLayout.addWidget( lineEdit1 ) mainLayout.addWidget( lineEdit2 ) mainLayout.addWidget( lineEdit3 ) mainLayout.addWidget( verticalSeparator ) mainLayout.addWidget( checkBox ) validator = QDoubleValidator( -10000.0, 10000.0, 2 ) lineEdit1.setValidator( validator ) lineEdit2.setValidator( validator ) lineEdit3.setValidator( validator ) lineEdit1.setText( "0.0" ) lineEdit2.setText( "1.0" ) lineEdit3.setText( "0.0" ) checkBox.setChecked( True ) self.label = label; self.lineEdit1 = lineEdit1; self.lineEdit2 = lineEdit2; self.lineEdit3 = lineEdit3; self.checkBox = checkBox self.setVectorEnabled() QtCore.QObject.connect( checkBox, QtCore.SIGNAL( 'clicked()' ), self.setVectorEnabled )
def __init__(self, text, minValue, maxValue, defaultValue ): QWidget.__init__( self ) validator = QDoubleValidator(minValue, maxValue, 2, self ) mainLayout = QHBoxLayout( self ) checkBox = QCheckBox() checkBox.setFixedWidth( 115 ) checkBox.setText( text ) lineEdit = QLineEdit() lineEdit.setValidator( validator ) lineEdit.setText( str(defaultValue) ) slider = QSlider( QtCore.Qt.Horizontal ) slider.setMinimum( minValue*100 ) slider.setMaximum( maxValue*100 ) slider.setValue( defaultValue ) mainLayout.addWidget( checkBox ) mainLayout.addWidget( lineEdit ) mainLayout.addWidget( slider ) QtCore.QObject.connect( slider, QtCore.SIGNAL( 'valueChanged(int)' ), self.syncWidthLineEdit ) QtCore.QObject.connect( lineEdit, QtCore.SIGNAL( 'textChanged(QString)' ), self.syncWidthSlider ) QtCore.QObject.connect( checkBox, QtCore.SIGNAL( "clicked()" ), self.updateEnabled ) self.checkBox = checkBox self.slider = slider self.lineEdit = lineEdit self.updateEnabled()
def _setupUi(self): self.setMinimumWidth(800) self.setMinimumHeight(600) layout = QVBoxLayout() self.setLayout(layout) self.editPmCmd = QLineEdit() layout.addWidget(self.editPmCmd) self.modesWidget = QWidget() self.modesLayout = QHBoxLayout() self.modesWidget.setLayout(self.modesLayout) layout.addWidget(self.modesWidget) self.checkBoxes = [] for mode in 'create query edit'.split(): chkBox = QCheckBox(mode) chkBox.setProperty('mode', mode) self.checkBoxes.append(chkBox) for checkBox in self.checkBoxes: self.modesLayout.addWidget(checkBox) checkBox.setChecked(True) if self.command: self.updateDocs() else: layout.addStretch()
def create_checkbox(self, parent, label=""): """ Returns an adapted checkbox control. """ control = QCheckBox(check_parent(parent)) control.setText(label) return control_adapter_for(control)
def _initUI(self): # Variables result = self.result() transitions = sorted(result.iter_transitions()) transition0 = transitions[0] model = _TransitionListModel(transitions) # Widgets self._chk_errorbar = QCheckBox("Show error bars") self._chk_errorbar.setChecked(True) self._cb_transition = QComboBox() self._cb_transition.setModel(model) self._cb_transition.setCurrentIndex(0) self._chk_pg = QCheckBox("No absorption, no fluorescence") state = result.exists(transition0, True, False, False, False) self._chk_pg.setEnabled(state) self._chk_pg.setChecked(state) self._chk_eg = QCheckBox("With absorption, no fluorescence") state = result.exists(transition0, True, True, False, False) self._chk_eg.setEnabled(state) self._chk_eg.setChecked(state) self._chk_pt = QCheckBox("No absorption, with fluorescence") state = result.exists(transition0, True, False, True, True) self._chk_pt.setEnabled(state) self._chk_pt.setChecked(state) self._chk_et = QCheckBox("With absorption, with fluorescence") state = result.exists(transition0, True, True, True, True) self._chk_et.setEnabled(state) self._chk_et.setChecked(state) # Layouts layout = _ResultToolItem._initUI(self) layout.addRow(self._chk_errorbar) layout.addRow("Transition", self._cb_transition) boxlayout = QVBoxLayout() boxlayout.addWidget(self._chk_pg) boxlayout.addWidget(self._chk_eg) boxlayout.addWidget(self._chk_pt) boxlayout.addWidget(self._chk_et) box_generated = QGroupBox("Curves") box_generated.setLayout(boxlayout) layout.addRow(box_generated) # Signals self._cb_transition.currentIndexChanged.connect(self._onTransitionChanged) self._chk_pg.stateChanged.connect(self.stateChanged) self._chk_eg.stateChanged.connect(self.stateChanged) self._chk_pt.stateChanged.connect(self.stateChanged) self._chk_et.stateChanged.connect(self.stateChanged) self._chk_errorbar.stateChanged.connect(self.stateChanged) return layout
def __init__(self, renderController, parent=None): super(RenderSlicerParamWidget, self).__init__(parent=parent) self.renderController = renderController self.renderController.slicesChanged.connect(self.setSlices) self.renderController.clippingBoxChanged.connect(self.showsClippingBox) self.renderController.clippingPlanesChanged.connect(self.showsClippingPlanes) self.sliceLabelTexts = ["Axial:", "Coronal:", "Sagittal:"] self.sliceLabels = [QLabel(text) for text in self.sliceLabelTexts] self.sliceCheckBoxes = [QCheckBox() for i in range(3)] for index in range(3): self.sliceCheckBoxes[index].clicked.connect(self.checkBoxChanged) self.sliceLabels[index].setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.sliceCheckBoxes[index].setEnabled(True) slicesLayout = QGridLayout() slicesLayout.setAlignment(Qt.AlignTop) for index in range(3): slicesLayout.addWidget(self.sliceLabels[index], index+1, 0) slicesLayout.addWidget(self.sliceCheckBoxes[index], index+1, 1) self.slicesGroupBox = QGroupBox() self.slicesGroupBox.setTitle("Visible slices") self.slicesGroupBox.setLayout(slicesLayout) # Create option to show clipping box self.clippingCheckBox = QCheckBox() self.clippingCheckBox.setChecked(self.renderController.clippingBox) self.clippingCheckBox.clicked.connect(self.clippingCheckBoxChanged) self.clippingPlanesCheckBox = QCheckBox() self.clippingPlanesCheckBox.setChecked(self.renderController.clippingPlanes) self.clippingPlanesCheckBox.clicked.connect(self.clippingPlanesCheckBoxChanged) self.resetButton = QPushButton("Reset") self.resetButton.clicked.connect(self.resetClippingBox) clippingLabel = QLabel("Clipping box:") clippingLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter) clippingPlanesLabel = QLabel("Clipping planes:") clippingPlanesLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter) clipLayout = QGridLayout() clipLayout.addWidget(clippingLabel, 0, 0) clipLayout.addWidget(self.clippingCheckBox, 0, 1) clipLayout.addWidget(clippingPlanesLabel, 1, 0) clipLayout.addWidget(self.clippingPlanesCheckBox, 1, 1) clipLayout.addWidget(self.resetButton, 2, 0) self.clippingGroupBox = QGroupBox() self.clippingGroupBox.setTitle("Clipping box") self.clippingGroupBox.setLayout(clipLayout) # Create a nice layout for the labels layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.addWidget(self.slicesGroupBox, 0, 0) layout.addWidget(self.clippingGroupBox, 0, 1) self.setLayout(layout)
def __init__(self, color, diameter, parent=None): QCheckBox.__init__(self, parent) self.color1 = QColor(color) self.color2 = QColor(50, 50, 50) self.resize(QSize(2 * float(diameter), diameter)) self.setStyleSheet("background-color: rgb(0, 0, 0);\n" + "color: rgb(255, 255, 255);\n") self.setChecked(True) self.setEnabled(True) self._enable = True
def testSignalMapper(self): checkboxMapper = QSignalMapper() box = QCheckBox('check me') box.stateChanged.connect(checkboxMapper.map) checkboxMapper.setMapping(box, box.text()) checkboxMapper.mapped[str].connect(self.cb_changed) self._changed = False box.setChecked(True) self.assert_(self._changed)
class _PhotonSpectrumResultOptionsToolItem(_ResultToolItem): def _initUI(self): # Widgets self._chk_total = QCheckBox("Show total intensity") self._chk_total.setChecked(True) self._chk_background = QCheckBox("Show background intensity") self._chk_background.setChecked(False) self._chk_errorbar = QCheckBox("Show error bars") self._chk_errorbar.setChecked(True) # Layouts layout = _ResultToolItem._initUI(self) layout.addRow(self._chk_total) layout.addRow(self._chk_background) layout.addRow(self._chk_errorbar) # Signals self._chk_total.stateChanged.connect(self.stateChanged) self._chk_background.stateChanged.connect(self.stateChanged) self._chk_errorbar.stateChanged.connect(self.stateChanged) return layout def isTotal(self): return self._chk_total.isChecked() def isBackground(self): return self._chk_background.isChecked() def isErrorbar(self): return self._chk_errorbar.isChecked()
class EditPreferencesDlg(QDialog): def __init__(self, parent=None): super(EditPreferencesDlg, self).__init__(parent) self.setWindowTitle("Preferences") # define widgets pref_list = QListWidget() pref_list.addItem("General") pref_list.addItem("Display") pref_list.setMaximumWidth(150) pref_list.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) general_page = QWidget() general_layout = QGridLayout() general_layout.setAlignment(Qt.AlignTop) general_layout.addWidget(QLabel("<b>General</b>"), 0, 0) general_page.setLayout(general_layout) display_page = QWidget() display_layout = QGridLayout() display_layout.setAlignment(Qt.AlignTop) display_layout.addWidget(QLabel("<b>Display Options</b>"), 0, 0) self.multitabs_checkbox = QCheckBox("Limit the display of tabs to one relief device (and the device's scenarios) at a time") if parent.limit_tabs is True: self.multitabs_checkbox.setChecked(True) display_layout.addWidget(self.multitabs_checkbox, 1, 0) display_page.setLayout(display_layout) stacked_widget = QStackedWidget() for page in general_page, display_page: stacked_widget.addWidget(page) main_layout = QVBoxLayout() widgets_layout = QHBoxLayout() widgets_layout.addWidget(pref_list) widgets_layout.addWidget(stacked_widget) buttons_layout = QHBoxLayout() buttons_layout.addStretch() buttons_layout.addWidget(button_box) main_layout.addLayout(widgets_layout) main_layout.addLayout(buttons_layout) self.setLayout(main_layout) pref_list.currentRowChanged.connect(stacked_widget.setCurrentIndex) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) def sizeHint(self): return QSize(400, 400) def returnVals(self): return self.multitabs_checkbox.isChecked()
def addReadinessTab(self): self.readyFrame = QtGui.QFrame() self.readyLayout = QtGui.QVBoxLayout() self.readyFrame.setLayout(self.readyLayout) # Initial state self.readyInitialGroup = QtGui.QGroupBox(u"Initial readiness state") self.readyInitialLayout = QtGui.QVBoxLayout() self.readyInitialGroup.setLayout(self.readyInitialLayout) self.readyatstartCheckbox = QCheckBox(getMessage("readyatstart-label")) self.readyatstartCheckbox.setObjectName("readyAtStart") self.readyInitialLayout.addWidget(self.readyatstartCheckbox) self.readyLayout.addWidget(self.readyInitialGroup) # Automatically pausing self.readyPauseGroup = QtGui.QGroupBox(u"Pausing") self.readyPauseLayout = QtGui.QVBoxLayout() self.readyPauseGroup.setLayout(self.readyPauseLayout) self.pauseonleaveCheckbox = QCheckBox(getMessage("pauseonleave-label")) self.pauseonleaveCheckbox.setObjectName("pauseOnLeave") self.readyPauseLayout.addWidget(self.pauseonleaveCheckbox) self.readyLayout.addWidget(self.readyPauseGroup) # Unpausing self.readyUnpauseGroup = QtGui.QGroupBox(getMessage("unpause-title")) self.readyUnpauseLayout = QtGui.QVBoxLayout() self.readyUnpauseGroup.setLayout(self.readyUnpauseLayout) self.readyUnpauseButtonGroup = QButtonGroup() self.unpauseIfAlreadyReadyOption = QRadioButton(getMessage("unpause-ifalreadyready-option")) self.readyUnpauseButtonGroup.addButton(self.unpauseIfAlreadyReadyOption) self.unpauseIfAlreadyReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png")) self.unpauseIfAlreadyReadyOption.setObjectName("unpause-ifalreadyready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFALREADYREADY_MODE) self.readyUnpauseLayout.addWidget(self.unpauseIfAlreadyReadyOption) self.unpauseIfOthersReadyOption = QRadioButton(getMessage("unpause-ifothersready-option")) self.readyUnpauseButtonGroup.addButton(self.unpauseIfOthersReadyOption) self.unpauseIfOthersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png")) self.unpauseIfOthersReadyOption.setObjectName("unpause-ifothersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFOTHERSREADY_MODE) self.readyUnpauseLayout.addWidget(self.unpauseIfOthersReadyOption) self.unpauseIfMinUsersReadyOption = QRadioButton(getMessage("unpause-ifminusersready-option")) self.readyUnpauseButtonGroup.addButton(self.unpauseIfMinUsersReadyOption) self.unpauseIfMinUsersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png")) self.unpauseIfMinUsersReadyOption.setObjectName("unpause-ifminusersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFMINUSERSREADY_MODE) self.readyUnpauseLayout.addWidget(self.unpauseIfMinUsersReadyOption) self.unpauseAlwaysUnpauseOption = QRadioButton(getMessage("unpause-always")) self.readyUnpauseButtonGroup.addButton(self.unpauseAlwaysUnpauseOption) self.unpauseAlwaysUnpauseOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png")) self.unpauseAlwaysUnpauseOption.setObjectName("unpause-always" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_ALWAYS_MODE) self.readyUnpauseLayout.addWidget(self.unpauseAlwaysUnpauseOption) self.readyLayout.addWidget(self.readyUnpauseGroup) self.readyLayout.setAlignment(Qt.AlignTop) self.stackedLayout.addWidget(self.readyFrame)
def __init__(self, view): super(SelectionOptions, self).__init__() self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) self.view = view self.view.scene().selectionChanged.connect(self.updateOptions) self.gridLayout = QGridLayout(self) self.nameLabel = QLabel(self.str_name, self) self.gridLayout.addWidget(self.nameLabel, 0, 0, 1, 1) self.nameLE = QLineEdit(self) self.gridLayout.addWidget(self.nameLE, 0, 1, 1, 2) self.nameLE.returnPressed.connect(self.setItemName) self.showNameLabel = QLabel(self.str_showName, self) self.gridLayout.addWidget(self.showNameLabel, 1, 0, 1, 1) self.showNameCB = QCheckBox(self) self.gridLayout.addWidget(self.showNameCB, 1, 1, 1, 1) self.showNameCB.stateChanged.connect(self.setNameVisibility) self.showCategoryLabel = QLabel(self.str_showCategory, self) self.gridLayout.addWidget(self.showCategoryLabel, 2, 0, 1, 1) self.showCategoryCB = QCheckBox(self) self.gridLayout.addWidget(self.showCategoryCB, 2, 1, 1, 1) self.showCategoryCB.stateChanged.connect(self.setCategoryVisibility) self.nbInputsLabel = QLabel(self.str_nbInputs, self) self.gridLayout.addWidget(self.nbInputsLabel, 3, 0, 1, 1) self.nbInputsCB = QComboBox(self) self.nbInputsCB.activated.connect(self.setNbInputs) self.nbInputsCB.addItems([str(x) for x in range(2, 33)]) self.gridLayout.addWidget(self.nbInputsCB, 3, 1, 1, 2) self.orientLabel = QLabel(self.str_orientation, self) self.gridLayout.addWidget(self.orientLabel, 4, 0, 1, 1) self.cwRotationButton = QPushButton(self) self.cwRotationButton.setText("↻") self.cwRotationButton.clicked.connect( lambda: self.view.rotateItems(90)) self.gridLayout.addWidget(self.cwRotationButton, 4, 1, 1, 1) self.acwRotationButton = QPushButton(self) self.acwRotationButton.setText("↺") self.acwRotationButton.clicked.connect( lambda: self.view.rotateItems(-90)) self.gridLayout.addWidget(self.acwRotationButton, 4, 2, 1, 1) self.updateOptions()
def addSyncTab(self): self.syncSettingsFrame = QtGui.QFrame() self.syncSettingsLayout = QtGui.QVBoxLayout() self.desyncSettingsGroup = QtGui.QGroupBox(getMessage("sync-otherslagging-title")) self.desyncOptionsFrame = QtGui.QFrame() self.desyncSettingsOptionsLayout = QtGui.QHBoxLayout() config = self.config self.slowdownCheckbox = QCheckBox(getMessage("slowondesync-label")) self.slowdownCheckbox.setObjectName("slowOnDesync") self.rewindCheckbox = QCheckBox(getMessage("rewindondesync-label")) self.rewindCheckbox.setObjectName("rewindOnDesync") self.fastforwardCheckbox = QCheckBox(getMessage("fastforwardondesync-label")) self.fastforwardCheckbox.setObjectName("fastforwardOnDesync") self.desyncSettingsLayout = QtGui.QGridLayout() self.desyncSettingsLayout.setSpacing(2) self.desyncFrame = QtGui.QFrame() self.desyncFrame.setLineWidth(0) self.desyncFrame.setMidLineWidth(0) self.desyncSettingsLayout.addWidget(self.slowdownCheckbox, 0, 0, 1, 2, Qt.AlignLeft) self.desyncSettingsLayout.addWidget(self.rewindCheckbox, 1, 0,1,2, Qt.AlignLeft) self.desyncSettingsLayout.setAlignment(Qt.AlignLeft) self.desyncSettingsGroup.setLayout(self.desyncSettingsLayout) self.desyncSettingsOptionsLayout.addWidget(self.desyncFrame) self.desyncFrame.setLayout(self.syncSettingsLayout) self.othersyncSettingsGroup = QtGui.QGroupBox(getMessage("sync-youlaggging-title")) self.othersyncOptionsFrame = QtGui.QFrame() self.othersyncSettingsLayout = QtGui.QGridLayout() self.dontslowwithmeCheckbox = QCheckBox(getMessage("dontslowdownwithme-label")) self.dontslowwithmeCheckbox.setObjectName("dontSlowDownWithMe") self.othersyncSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 2, 0, 1, 2, Qt.AlignLeft) self.othersyncSettingsLayout.setAlignment(Qt.AlignLeft) self.othersyncSettingsLayout.addWidget(self.fastforwardCheckbox, 3, 0,1,2, Qt.AlignLeft) self.othersyncSettingsGroup.setLayout(self.othersyncSettingsLayout) self.othersyncSettingsGroup.setMaximumHeight(self.othersyncSettingsGroup.minimumSizeHint().height()) self.syncSettingsLayout.addWidget(self.othersyncSettingsGroup) self.syncSettingsLayout.addWidget(self.desyncSettingsGroup) self.syncSettingsFrame.setLayout(self.syncSettingsLayout) self.desyncSettingsGroup.setMaximumHeight(self.desyncSettingsGroup.minimumSizeHint().height()) self.syncSettingsLayout.setAlignment(Qt.AlignTop) self.stackedLayout.addWidget(self.syncSettingsFrame)
class CheckWithHelp(QHBoxLayout): def __init__(self, the_text, help_dict = None, help_instance = None): QHBoxLayout.__init__(self) # new_layout = QHBoxLayout() self.cb = QCheckBox(the_text) self.cb.setFont(QFont('SansSerif', 12)) self.addWidget(self.cb) if help_dict != None: if the_text in help_dict.keys(): if (help_instance == None): print "No help instance specified." else: help_button_widget = help_instance.create_button(the_text, help_dict[the_text]) self.addWidget(help_button_widget)
def create_check_boxes(self, name_list): for txt in name_list: qh = QHBoxLayout() cb = QCheckBox(txt) cb.setFont(regular_small_font) qh.addWidget(cb) qh.addStretch() self.the_layout.addLayout(qh) if self.handler != None: cb.toggled.connect(self.handler) self.widget_dict[txt] = cb if (self.help_dict != None) and (self.help_instance != None): if txt in self.help_dict: help_button_widget = self.help_instance.create_button(txt, self.help_dict[txt]) qh.addWidget(help_button_widget)
def __init__(self, *args, **kwargs): super(HotkeyDialogView, self).__init__(*args, **kwargs) self.setWindowTitle("Set Hotkey") self.edit_line = QLineEdit() self.edit_line.setEnabled(False) self.installEventFilter(self) self.ok_btn = QPushButton("&Ok") # noinspection PyUnresolvedReferences self.ok_btn.clicked.connect(self.accept) self.control_check = QCheckBox() self.control_label = QLabel("CTRL") self.shift_check = QCheckBox() self.shift_label = QLabel("SHIFT") self.alt_check = QCheckBox() self.alt_label = QLabel("ALT") self.cancel_btn = QPushButton("&Cancel") # noinspection PyUnresolvedReferences self.cancel_btn.clicked.connect(self.reject) self.h_keys_layout = QHBoxLayout() self.h_btn_layout = QHBoxLayout() self.v_layout = QVBoxLayout() self.h_btn_layout.addStretch(0) self.h_btn_layout.addWidget(self.ok_btn) self.h_btn_layout.addWidget(self.cancel_btn) self.h_keys_layout.addWidget(self.control_check) self.h_keys_layout.addWidget(self.control_label) self.h_keys_layout.addWidget(self.shift_check) self.h_keys_layout.addWidget(self.shift_label) self.h_keys_layout.addWidget(self.alt_check) self.h_keys_layout.addWidget(self.alt_label) self.h_keys_layout.addWidget(self.edit_line) self.v_layout.addLayout(self.h_keys_layout) self.v_layout.addLayout(self.h_btn_layout) self.setLayout(self.v_layout) # noinspection PyUnresolvedReferences self.accepted.connect(self.on_accept) # noinspection PyUnresolvedReferences self.rejected.connect(self.on_reject) self.__key = None
def _createWidgets(self): '''Create the widgets contained in this box''' # Peak number chooser self.numpeaks = [QRadioButton("2"), QRadioButton("3"), QRadioButton("4")] self.numpeaks[0].setToolTip(ttt('Model the exchange of 2 peaks')) self.numpeaks[1].setToolTip(ttt('Model the exchange of 3 peaks')) self.numpeaks[2].setToolTip(ttt('Model the exchange of 4 peaks')) # Make 4x4 matrix of QLabels self.exview = [[QLabel(self) for i in xrange(4)] for j in xrange(4)] for i in xrange(4): for e in self.exview[i]: e.setToolTip(ttt('The current exchange matrix')) # Enforce symmetry button self.symmetry = QCheckBox("Enforce Symmetry", self) self.symmetry.setToolTip(ttt('If symmetry is on then you only need to ' 'manually set the upper triangle of the ' 'exchange matrix. Thse values are ' 'mirrored ' 'in the lower triangle and the diagonals ' 'are automatically set so that each row ' 'sums to 1. ' 'Otherwise you must set every element')) # Exchange picker self.exchooser = QComboBox(self) self.exchooser.setToolTip(ttt('Choose between which two peaks to set ' 'the exchange (relative) rate')) # Exchange value self.exvalue = QLineEdit(self) self.exvalue.setToolTip(ttt('The exchange (relative) rate')) self.exvalue.setValidator(QDoubleValidator(0.0, 1.0, 3, self.exvalue))
def __init__(self,args,continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400,200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttons self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) #add the actions for quiting quit_action = QAction(self.window) quit_action.setShortcut('Ctrl+Q') quit_action.triggered.connect(self.accel_quit) self.window.addAction(quit_action)
def __init__(self, renderController, parent=None): super(RenderSlicerParamWidget, self).__init__(parent=parent) self.renderController = renderController self.renderController.slicesChanged.connect(self.setSlices) self.renderController.clippingBoxChanged.connect(self.showsClippingBox) self.slicesLabel = QLabel("Show slices for directions:") self.sliceLabelTexts = ["x:", "y:", "z:"] self.sliceLabels = [QLabel(text) for text in self.sliceLabelTexts] self.sliceCheckBoxes = [QCheckBox() for i in range(3)] for index in range(3): self.sliceCheckBoxes[index].clicked.connect(self.checkBoxChanged) self.sliceLabels[index].setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.sliceCheckBoxes[index].setEnabled(True) # Create a nice layout for the labels layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setColumnStretch(0, 1) layout.setColumnStretch(1, 3) layout.addWidget(self.slicesLabel, 0, 0, 1, -1) for index in range(3): layout.addWidget(self.sliceLabels[index], index+1, 0) layout.addWidget(self.sliceCheckBoxes[index], index+1, 1) # Create option to show clipping box self.clippingCheckBox = QCheckBox() self.clippingCheckBox.clicked.connect(self.clippingCheckBoxChanged) self.clippingLabel = QLabel("Clipping box:") self.clippingLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter) layout.addWidget(self.clippingLabel, 5, 0) layout.addWidget(self.clippingCheckBox, 5, 1) self.setLayout(layout)
def buildColorStepsControl(self): """Builds the portion of this widget for color cycling options.""" widget = QWidget() layout = QHBoxLayout() self.stepBox = QCheckBox(self.color_step_label) self.stepBox.stateChanged.connect(self.colorstepsChange) self.stepEdit = QLineEdit("8", self) # Setting max to sys.maxint in the validator causes an overflow! D: self.stepEdit.setValidator(QIntValidator(1, 65536, self.stepEdit)) self.stepEdit.setEnabled(False) self.stepEdit.editingFinished.connect(self.colorstepsChange) if self.color_step > 0: self.stepBox.setCheckState(Qt.Checked) self.stepEdit.setEnabled(True) layout.addWidget(self.stepBox) layout.addItem(QSpacerItem(5,5)) layout.addWidget(QLabel("with")) layout.addItem(QSpacerItem(5,5)) layout.addWidget(self.stepEdit) layout.addItem(QSpacerItem(5,5)) layout.addWidget(QLabel(self.number_steps_label)) widget.setLayout(layout) return widget
def __init__(self, name, arg_dict, pos = "side", max_size = 200): QWidget.__init__(self) self.setContentsMargins(1, 1, 1, 1) if pos == "side": self.layout1=QHBoxLayout() else: self.layout1 = QVBoxLayout() self.layout1.setContentsMargins(1, 1, 1, 1) self.layout1.setSpacing(1) self.setLayout(self.layout1) self.cbox = QCheckBox() # self.efield.setMaximumWidth(max_size) self.cbox.setFont(QFont('SansSerif', 12)) self.label = QLabel(name) # self.label.setAlignment(Qt.AlignLeft) self.label.setFont(QFont('SansSerif', 12)) self.layout1.addWidget(self.label) self.layout1.addWidget(self.cbox) self.arg_dict = arg_dict self.name = name self.mytype = type(self.arg_dict[name]) if self.mytype != bool: self.cbox.setChecked(bool(self.arg_dict[name])) else: self.cbox.setChecked(self.arg_dict[name]) self.cbox.toggled.connect(self.when_modified) self.when_modified()
def __init__(self, parent = None): super(SettingsPage, self).__init__(parent) self.setMinimumSize(800, 600) self.addProperty(grizzle.User, "email", 0, 0) self.addProperty(grizzle.User, "display_name", 1, 0) self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.dob", 2, 0) self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.gender", 3, 0, style = "radio") self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.height", 4, 0, min = 100, max = 240, suffix = "cm") self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.units", 5, 0, style = "radio") withingsB = QGroupBox("Withings Support", self) withingsL = QGridLayout(withingsB) self.enableWithings = QCheckBox("Enable Withings", withingsB) self.enableWithings.toggled.connect(self.toggleWithings) withingsL.addWidget(self.enableWithings, 0, 0) withingsL.addWidget(QLabel("Withings User ID"), 1, 0) self.withingsUserID = QLineEdit(withingsB) withingsL.addWidget(self.withingsUserID, 1, 1) withingsL.addWidget(QLabel("Withings Key"), 2, 0) self.withingsKey = QLineEdit(withingsB) withingsL.addWidget(self.withingsKey, 2, 1) self.addWidget(withingsB, self.form.rowCount(), 0, 1, 2) self.addStretch() self.statusMessage.connect(QCoreApplication.instance().status_message)
class IncludeRow(): def __init__(self,result): self.result = result self.resultLabel = QLabel(result) self.included = QCheckBox() def isIncluded(self): return self.included.isChecked()
class _ChannelsResultOptionsToolItem(_ResultToolItem): def _initUI(self): # Widgets self._chk_errorbar = QCheckBox("Show error bars") self._chk_errorbar.setChecked(True) # Layouts layout = _ResultToolItem._initUI(self) layout.addRow(self._chk_errorbar) # Signals self._chk_errorbar.stateChanged.connect(self.stateChanged) return layout def showErrorbar(self): return self._chk_errorbar.isChecked()
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Select analysis file button button = QPushButton('Select analysis file', self) button.setToolTip('*.inp CalculiX analysis file.') button.move(10, 10) button.clicked.connect(self.on_click) # Text box - file path and name self.textbox_file_name = QLineEdit(self) self.textbox_file_name.move(120, 15) self.textbox_file_name.resize(420, 20) self.textbox_file_name.setText("None analysis file selected") self.textbox_file_name.setToolTip('Analysis file.') # Update button button1 = QPushButton('Update domains', self) button1.setToolTip( 'Update naming inputs and material data from FreeCAD.') button1.move(10, 50) button1.clicked.connect(self.on_click1) # Domains definition # Label above domains definition label21 = QLabel('Domain 0', self) label21.setStyleSheet("font-weight: bold") label21.move(120, 50) label21 = QLabel('Domain 1', self) label21.setStyleSheet("font-weight: bold") label21.move(260, 50) label21 = QLabel('Domain 2', self) label21.setStyleSheet("font-weight: bold") label21.move(400, 50) label24 = QLabel('Material object', self) label24.move(20, 80) label25 = QLabel('Thickness object', self) label25.move(20, 110) label26 = QLabel('As design domain', self) label26.move(20, 140) label27 = QLabel('Stress limit [MPa]', self) label27.move(20, 170) # Combo box - select domain by material object self.combo = QComboBox(self) self.combo.setToolTip('Material object to define the domain.') self.combo.move(120, 80) self.combo.resize(140, 30) self.combo.currentIndexChanged.connect(self.on_change) self.combo1 = QComboBox(self) self.combo1.setToolTip('Material object to define the domain.') self.combo1.move(260, 80) self.combo1.resize(140, 30) self.combo1.currentIndexChanged.connect(self.on_change1) self.combo2 = QComboBox(self) self.combo2.setToolTip('Material object to define the domain.') self.combo2.move(400, 80) self.combo2.resize(140, 30) self.combo2.currentIndexChanged.connect(self.on_change2) # Combo box - select thickness object self.combo0t = QComboBox(self) self.combo0t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo0t.move(120, 110) self.combo0t.resize(140, 30) self.combo1t = QComboBox(self) self.combo1t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo1t.move(260, 110) self.combo1t.resize(140, 30) self.combo2t = QComboBox(self) self.combo2t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo2t.move(400, 110) self.combo2t.resize(140, 30) self.textbox3 = QLineEdit(self) self.textbox3.move(120, 170) self.textbox3.resize(40, 20) # self.textbox3.setText("") self.textbox3.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox4 = QLineEdit(self) self.textbox4.move(260, 170) self.textbox4.resize(40, 20) # self.textbox4.setText("") self.textbox4.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox5 = QLineEdit(self) self.textbox5.move(400, 170) self.textbox5.resize(40, 20) # self.textbox5.setText("") self.textbox5.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') # Check box - design or nondesign self.checkbox = QCheckBox('', self) self.checkbox.setChecked(True) self.checkbox.setToolTip('Check to be the design domain.') self.checkbox.move(120, 140) self.checkbox1 = QCheckBox('', self) self.checkbox1.setChecked(True) self.checkbox1.setToolTip('Check to be the design domain.') self.checkbox1.move(260, 140) self.checkbox2 = QCheckBox('', self) self.checkbox2.setChecked(True) self.checkbox2.setToolTip('Check to be the design domain.') self.checkbox2.move(400, 140) # Text box - stress limit self.textbox = QLineEdit(self) self.textbox.move(120, 170) self.textbox.resize(40, 20) # self.textbox.setText("") self.textbox.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox1 = QLineEdit(self) self.textbox1.move(260, 170) self.textbox1.resize(40, 20) # self.textbox1.setText("") self.textbox1.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox2 = QLineEdit(self) self.textbox2.move(400, 170) self.textbox2.resize(40, 20) # self.textbox2.setText("") self.textbox2.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) # Filters # Label above filter definition label31 = QLabel('Filter 0', self) label31.setStyleSheet("font-weight: bold") label31.move(120, 210) label32 = QLabel('Filter 1', self) label32.setStyleSheet("font-weight: bold") label32.move(260, 210) label33 = QLabel('Filter 2', self) label33.setStyleSheet("font-weight: bold") label33.move(400, 210) label34 = QLabel('Type', self) label34.move(20, 240) label35 = QLabel('Range [mm]', self) label35.move(20, 270) label36 = QLabel('Direction vector', self) label36.move(20, 300) label37 = QLabel('Apply to', self) label37.move(20, 330) # Combo box - select filter type self.combo6 = QComboBox(self) self.combo6.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo6.addItem("None") self.combo6.addItem("simple") self.combo6.addItem("casting") self.combo6.setCurrentIndex(1) self.combo6.move(120, 240) self.combo6.currentIndexChanged.connect(self.on_change6) self.combo7 = QComboBox(self) self.combo7.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo7.addItem("None") self.combo7.addItem("simple") self.combo7.addItem("casting") self.combo7.move(260, 240) self.combo7.currentIndexChanged.connect(self.on_change7) self.combo8 = QComboBox(self) self.combo8.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo8.addItem("None") self.combo8.addItem("simple") self.combo8.addItem("casting") self.combo8.move(400, 240) self.combo8.currentIndexChanged.connect(self.on_change8) # Text box - filter range self.textbox6 = QLineEdit(self) self.textbox6.move(120, 270) self.textbox6.resize(50, 20) # self.textbox6.setText("") self.textbox6.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7 = QLineEdit(self) self.textbox7.move(260, 270) self.textbox7.resize(50, 20) # self.textbox7.setText("") self.textbox7.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7.setEnabled(False) self.textbox8 = QLineEdit(self) self.textbox8.move(400, 270) self.textbox8.resize(50, 20) # self.textbox8.setText("") self.textbox8.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox8.setEnabled(False) # Text box - casting direction self.textbox9 = QLineEdit(self) self.textbox9.move(120, 300) self.textbox9.resize(80, 20) self.textbox9.setText("0, 0, 1") self.textbox9.setEnabled(False) self.textbox9.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox10 = QLineEdit(self) self.textbox10.move(260, 300) self.textbox10.resize(80, 20) self.textbox10.resize(80, 20) self.textbox10.setText("0, 0, 1") self.textbox10.setEnabled(False) self.textbox10.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox11 = QLineEdit(self) self.textbox11.move(400, 300) self.textbox11.resize(80, 20) self.textbox11.setText("0, 0, 1") self.textbox11.setEnabled(False) self.textbox11.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') # list widget - select domains self.widget = QListWidget(self) self.widget.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget.move(120, 330) self.widget.resize(140, 120) self.widget.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1 = QListWidget(self) self.widget1.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget1.move(260, 330) self.widget1.resize(140, 120) self.widget1.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1.setEnabled(False) self.widget2 = QListWidget(self) self.widget2.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget2.move(400, 330) self.widget2.resize(140, 120) self.widget2.setSelectionMode(QAbstractItemView.MultiSelection) self.widget2.setEnabled(False) # Other settings label40 = QLabel('Other settings', self) label40.setStyleSheet("font-weight: bold") label40.move(10, 470) # AR, RR slider label41 = QLabel('Change per iteration: low', self) label41.setFixedWidth(150) label41.move(10, 500) label42 = QLabel('high', self) label42.move(240, 500) self.slider = QSlider(Qt.Horizontal, self) self.slider.setRange(1, 3) self.slider.setSingleStep(1) self.slider.setValue(2) self.slider.move(150, 500) self.slider.resize(80, 30) self.slider.setToolTip( 'Sets mass change per iteration, which is controlled as\n' 'slow: mass_addition_ratio=0.01, mass_removal_ratio=0.02\n' 'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n' 'fast: mass_addition_ratio=0.03, mass_removal_ratio=0.06') # optimization base combobox label51 = QLabel('Optimization base', self) label51.move(10, 530) self.combo51 = QComboBox(self) self.combo51.setToolTip( 'Basic principle to determine if element should remain or be removed:\n' '"stiffness" to maximize stiffness (minimize compliance),\n' '"heat" to maximize heat flow.') self.combo51.addItem("stiffness") self.combo51.addItem("heat") self.combo51.move(120, 530) # mass goal ratio label52 = QLabel('Mass goal ratio', self) label52.move(10, 560) self.textbox52 = QLineEdit(self) self.textbox52.move(120, 560) self.textbox52.resize(50, 20) self.textbox52.setText("0.4") self.textbox52.setToolTip( 'Fraction of all design domains masses to be achieved;\n' 'between 0 and 1.') # generate conf. file button button21 = QPushButton('Generate conf. file', self) button21.setToolTip( 'Writes configuration file with optimization parameters.') button21.move(10, 600) button21.clicked.connect(self.on_click21) # edit conf. file button button22 = QPushButton('Edit conf. file', self) button22.setToolTip('Opens configuration file for hand modifications.') button22.move(10, 630) button22.clicked.connect(self.on_click22) # run optimization button button23 = QPushButton('Run optimization', self) button23.setToolTip('Writes configuration file and runs optimization.') button23.move(10, 660) button23.clicked.connect(self.on_click23) # generate conf file and run optimization button button24 = QPushButton('Generate conf.\nfile and run\noptimization', self) button24.setToolTip('Writes configuration file and runs optimization.') button24.move(120, 600) button24.resize(100, 90) button24.clicked.connect(self.on_click24) # help buttons label41 = QLabel('Help', self) label41.move(440, 560) button31 = QPushButton('Example', self) button31.setToolTip( 'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD') button31.move(440, 590) # button31.resize(80, 50) button31.clicked.connect(self.on_click31) button32 = QPushButton('Conf. comments', self) button32.setToolTip( 'https://github.com/fandaL/beso/blob/master/beso_conf.py') button32.move(440, 620) # button32.resize(80, 50) button32.clicked.connect(self.on_click32) button33 = QPushButton('Close', self) button33.move(440, 690) # button33.resize(80, 50) button33.clicked.connect(self.on_click33) # open log file button40 = QPushButton('Open log file', self) button40.setToolTip('Opens log file in your text editor.\n' '(Does not refresh automatically.)') button40.move(10, 690) button40.clicked.connect(self.on_click40) self.on_click1() # first update self.show()
class MovementEditor(QWidget): def __init__(self): QWidget.__init__(self) self.setGeometry(QRect(100, 100, 400, 200)) self.layout = QtGui.QGridLayout(self) #lblAssetType self.lblAssetType = QLabel("Asset Type") self.layout.addWidget(self.lblAssetType, 0, 0) #cmdAssetType self.cmdAssetType = QComboBox(self) self.cmdAssetType.addItems(DaoAsset().getAssetTypes()) self.layout.addWidget(self.cmdAssetType, 0, 1) #lblAssetName self.lblAssetName = QLabel("Asset Name") self.layout.addWidget(self.lblAssetName, 1, 0) #cmdAssetName self.cmdAssetName = QComboBox(self) self.layout.addWidget(self.cmdAssetName, 1, 1) #lblCustody self.lblCustody = QLabel("Custody") self.layout.addWidget(self.lblCustody, 2, 0) #cmbCustody self.cmbCustody = QComboBox(self) custodyList = DaoCustody().getCustodyList() for (row) in custodyList: self.cmbCustody.addItem(row[1], row[0]) self.layout.addWidget(self.cmbCustody, 2, 1) #lblBuySell self.lblBuySell = QLabel("Buy Sell") self.layout.addWidget(self.lblBuySell, 3, 0) #cmdBuySell self.cmdBuySell = QComboBox(self) self.cmdBuySell.addItem("BUY") self.cmdBuySell.addItem("SELL") self.layout.addWidget(self.cmdBuySell, 3, 1) #lblByAmount self.lblByAmount = QLabel("By Amount") self.layout.addWidget(self.lblByAmount, 4, 0) #chkByAmount self.chkByAmount = QCheckBox(self) self.layout.addWidget(self.chkByAmount, 4, 1) #lblGrossAmount self.lblGrossAmount = QLabel("Gross Amount") self.layout.addWidget(self.lblGrossAmount, 5, 0) #txtGrossAmount self.txtGrossAmount = QLineEdit(self) self.txtGrossAmount.setValidator(QDoubleValidator( 0, 99999999, 6, self)) self.layout.addWidget(self.txtGrossAmount, 5, 1) #lblAcquisitionDate self.lblAcquisitionDate = QLabel("Acquisition Date") self.layout.addWidget(self.lblAcquisitionDate, 6, 0) #cmdAcquisitionDate self.dateAcquisitionDate = QDateEdit(self) self.dateAcquisitionDate.setDisplayFormat("dd-MM-yyyy") self.dateAcquisitionDate.setDate(datetime.datetime.now()) self.layout.addWidget(self.dateAcquisitionDate, 6, 1) #lblQuantity self.lblQuantity = QLabel("Quantity") self.layout.addWidget(self.lblQuantity, 7, 0) #txtQuantity self.txtQuantity = QLineEdit(self) self.txtQuantity.setValidator(QIntValidator(0, 1000000000, self)) self.layout.addWidget(self.txtQuantity, 7, 1) #lblPrice self.lblPrice = QLabel("Price") self.layout.addWidget(self.lblPrice, 8, 0) #txtPrice self.txtPrice = QLineEdit(self) self.txtPrice.setValidator(QDoubleValidator(0, 99999999, 6, self)) self.layout.addWidget(self.txtPrice, 8, 1) #lblRate self.lblRate = QLabel("Rate") self.layout.addWidget(self.lblRate, 9, 0) #txtRate self.txtRate = QLineEdit(self) self.txtRate.setValidator(QDoubleValidator(0, 99999999, 4, self)) self.txtRate.setEnabled(0) self.layout.addWidget(self.txtRate, 9, 1) #lblNetAmount self.lblNetAmount = QLabel("Net Amount") self.layout.addWidget(self.lblNetAmount, 10, 0) #txtNetAmount self.txtNetAmount = QLineEdit(self) self.txtNetAmount.setEnabled(0) self.txtNetAmount.setValidator(QDoubleValidator(0, 99999999, 6, self)) self.layout.addWidget(self.txtNetAmount, 10, 1) #lblCommissionPercentage self.lblCommissionPercentage = QLabel("Commission Percentage") self.layout.addWidget(self.lblCommissionPercentage, 11, 0) #txtCommissionPercentage self.txtCommissionPercentage = QLineEdit(self) self.txtCommissionPercentage.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionPercentage, 11, 1) #lblCommissionAmount self.lblCommissionAmount = QLabel("Commission Amount") self.layout.addWidget(self.lblCommissionAmount, 12, 0) #txtCommissionAmmount self.txtCommissionAmount = QLineEdit(self) self.txtCommissionAmount.setEnabled(0) self.txtCommissionAmount.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionAmount, 12, 1) #lblCommissionAmount self.lblCommissionVATAmount = QLabel("Commission VAT Amount") self.layout.addWidget(self.lblCommissionVATAmount, 13, 0) #txtCommissionAmmount self.txtCommissionVATAmount = QLineEdit(self) self.txtCommissionVATAmount.setEnabled(0) self.txtCommissionVATAmount.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionVATAmount, 13, 1) #lblTenor self.lblTenor = QLabel("Tenor") self.layout.addWidget(self.lblTenor, 14, 0) #txtTenor self.txtTenor = QLineEdit(self) self.txtTenor.setEnabled(0) self.txtTenor.setValidator(QDoubleValidator(0, 9999999, 0, self)) self.layout.addWidget(self.txtTenor, 14, 1) #btnAdd self.btnAdd = QPushButton("Add", self) self.layout.addWidget(self.btnAdd) #btnClear self.btnClear = QPushButton("Clear", self) self.layout.addWidget(self.btnClear) #clearEditor self.clearEditor() self.initListener() def initListener(self): self.cmdBuySell.connect( self.cmdBuySell, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.calculateNetAmount) self.chkByAmount.connect(self.chkByAmount, QtCore.SIGNAL("stateChanged(int)"), self.configEditorByAmount) self.txtGrossAmount.connect(self.txtGrossAmount, SIGNAL("editingFinished()"), self.calculatePrice) self.cmdAssetType.connect( self.cmdAssetType, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.configEditorByAssetType) self.txtQuantity.connect(self.txtQuantity, SIGNAL("textChanged(QString)"), self.calculateGrossAmount) self.txtQuantity.connect(self.txtQuantity, SIGNAL("textChanged(QString)"), self.calculatePrice) self.txtPrice.connect(self.txtPrice, SIGNAL("textChanged(QString)"), self.calculateGrossAmount) self.cmdAssetName.connect( self.cmdAssetName, SIGNAL("currentIndexChanged(const QString&)"), self.setDefaultCustody) self.txtCommissionPercentage.connect(self.txtCommissionPercentage, SIGNAL("textChanged(QString)"), self.calculateCommission) self.btnAdd.clicked.connect(self.addMovement) self.btnClear.clicked.connect(self.clearEditor) def addMovement(self): buySell = self.cmdBuySell.currentText() assetOID = self.cmdAssetName.itemData(self.cmdAssetName.currentIndex()) custodyOID = self.cmbCustody.itemData(self.cmbCustody.currentIndex()) acquisitionDate = self.dateAcquisitionDate.date() quantity = self.txtQuantity.text() if self.cmdAssetType.currentText() == 'BOND': rate = self.txtRate.text() if self.txtTenor.text() == '': tenor = None else: tenor = self.txtTenor.text() maturityDate = acquisitionDate.toPython() + datetime.timedelta( days=int(tenor)) else: rate = None maturityDate = None tenor = None price = self.txtPrice.text() grossAmount = self.txtGrossAmount.text() netAmount = self.txtNetAmount.text() commissionPercentage = self.txtCommissionPercentage.text() commissionAmount = self.txtCommissionAmount.text() commissionVATAmount = self.txtCommissionVATAmount.text() movement = Movement(None) movement.setAttr(None, assetOID, buySell, (acquisitionDate).toPython(), quantity, price, rate, grossAmount, netAmount, commissionPercentage, commissionAmount, commissionVATAmount, tenor, custodyOID, maturityDate, None, None) DaoMovement.insertMovement(movement) self.clearEditor() def clearEditor(self): #self.cmdAssetType.set self.txtQuantity.setText(None) self.txtPrice.setText(None) self.txtGrossAmount.setText("0") self.txtNetAmount.setText("0") self.txtRate.setText("0") #configDefaultCommission if self.cmdAssetType.currentText() == 'EQUITY': self.txtCommissionPercentage.setText( str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE)) else: self.txtCommissionPercentage.setText( str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE)) self.txtTenor.setText("") self.dateAcquisitionDate.setDate(datetime.datetime.now()) self.configEditorByAmount() self.configEditorByAssetType() def setDefaultCustody(self): defaultCustodyID = DaoCustody().getDefaultCustody( self.cmdAssetName.currentText()) for (row) in defaultCustodyID: self.cmbCustody.setCurrentIndex(self.cmbCustody.findData(row[0])) def configEditorByAssetType(self): self.cmdAssetName.clear() #loadAssetNames assetNameList = DaoAsset().getAssetNames( self.cmdAssetType.currentText()) for (assetName) in assetNameList: self.cmdAssetName.addItem(assetName[1], assetName[0]) #setPriceOrRate if self.cmdAssetType.currentText( ) == 'EQUITY' or self.cmdAssetType.currentText() == 'FUND': self.txtPrice.setEnabled(1) self.txtRate.setEnabled(0) self.txtRate.setText("0") self.txtTenor.setEnabled(0) self.txtTenor.setText(None) else: self.txtPrice.setEnabled(0) self.txtRate.setEnabled(1) self.txtPrice.setText("0") self.txtTenor.setEnabled(1) self.txtTenor.setText(None) #configDefaultCommission if self.cmdAssetType.currentText() == 'EQUITY': self.txtCommissionPercentage.setText( str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE)) else: self.txtCommissionPercentage.setText( str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE)) def configEditorByAmount(self): if self.chkByAmount.isChecked(): self.txtPrice.setEnabled(0) self.txtGrossAmount.setEnabled(1) else: self.txtPrice.setEnabled(1) self.txtGrossAmount.setEnabled(0) def calculateCommission(self): commissionPercentage = self.txtCommissionPercentage.text() grossAmount = self.txtGrossAmount.text() if commissionPercentage >= 0: commissionAmount = float(grossAmount) * float(commissionPercentage) self.txtCommissionAmount.setText( str('{0:.6f}'.format(commissionAmount))) commissionVATAmount = commissionAmount * Constant.CONST_IVA_PERCENTAGE self.txtCommissionVATAmount.setText( str('{0:.6f}'.format(commissionVATAmount))) self.calculateNetAmount() def calculatePrice(self): quantity = self.txtQuantity.text() amount = self.txtGrossAmount.text() if (quantity is not u"" or None) and (amount is not u"" or None): self.txtPrice.setText( str('{0:.6f}'.format(float(amount) / float(quantity)))) def calculateNetAmount(self): buySell = self.cmdBuySell.currentText() grossAmount = float(self.txtGrossAmount.text()) commissionAmount = float(self.txtCommissionAmount.text()) commissionVATAmount = float(self.txtCommissionVATAmount.text()) if buySell == 'BUY': netAmount = grossAmount + commissionVATAmount + commissionAmount else: netAmount = grossAmount - commissionVATAmount - commissionAmount self.txtNetAmount.setText(str(netAmount)) def calculateGrossAmount(self): quantity = self.txtQuantity.text() price = self.txtPrice.text() if (not self.chkByAmount.isChecked()) and ( quantity is not u"" or None) and (price is not u"" or None): self.txtGrossAmount.setText( str('{0:.6f}'.format(float(quantity) * float(price)))) self.calculateCommission()
class SettingsWindow(QDialog): def __init__(self, parent): super(self.__class__, self).__init__(parent) self.parent = parent self.lib = libserial.InitApp(self) if self.parent.receive is not None: self.boolean_config_is_ok = True else: self.boolean_config_is_ok = False self.config_parser = ConfigParser.ConfigParser() self.config_parser.read("config/profiles/profiles.ini") self.settings_parser = ConfigParser.ConfigParser() self.settings_parser.read('config/settings.ini') self.setWindowTitle(SERIAL_CHAT_SETTINGS_TITLE) self.button_box_dialog = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.button_box_dialog.button(QDialogButtonBox.Ok).setText(CONNECT) self.button_box_dialog.button(QDialogButtonBox.Cancel).setText(CANCEL) self.button_box_dialog.accepted.connect(self.accept) self.accepted.connect(self.apply_setting_changes) self.button_box_dialog.rejected.connect(self.reject) self.serial_dropdown = QComboBox() self.lib.init__serial() self.serial_values = self.lib.get_serials() for serials in self.serial_values: self.serial_dropdown.addItem(serials) if self.parent.serial_port is not None: self.serial_dropdown.setCurrentIndex( self.serial_dropdown.findText(self.parent.serial_port.name)) self.profiles_combobox = QComboBox() self.profiles_combobox.addItem("None") if self.parent.choosen_profile == "Custom": self.profiles_combobox.addItem("Custom") for profile in self.config_parser.sections(): self.profiles_combobox.addItem(profile) if self.parent.custom_settings: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('Custom')) elif self.parent.choosen_profile != 'None': self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText(self.parent.choosen_profile)) else: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('None')) self.profiles_combobox.currentIndexChanged.connect( self.change_custom_settings_on_profile) self.custom_settings_checkbox = QCheckBox() self.custom_settings_checkbox.stateChanged.connect( self.custom_settings_enable_disable) self.interval_time_lineedit = QLineEdit(str(self.parent.interval_time)) self.interval_time_lineedit.editingFinished.connect( self.check_if_digit) self.interval_time_lineedit.setDisabled(True) self.serial_speed_combobox = QComboBox() for sp in serial_speeds: self.serial_speed_combobox.addItem(str(sp)) if self.boolean_config_is_ok: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText( str(self.parent.serial_port.baudrate))) else: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText('9600')) self.serial_speed_combobox.setDisabled(True) self.databits_combobox = QComboBox() for db in bytesize_values: self.databits_combobox.addItem(str(db)) if self.boolean_config_is_ok: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText( str(self.parent.serial_port.bytesize))) else: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText('8')) self.databits_combobox.setDisabled(True) self.stopbits_combobox = QComboBox() for sb in stop_values: self.stopbits_combobox.addItem(str(sb)) if self.boolean_config_is_ok: sb = str(self.parent.serial_port.stopbits).replace('.', ',') self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText(str(sb))) else: self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText('1')) self.stopbits_combobox.setDisabled(True) self.parity_combobox = QComboBox() for par in parity_values: self.parity_combobox.addItem(str(par)) if self.boolean_config_is_ok: table = {'O': 'Odd', 'E': 'Even', 'N': 'None'} xxx = [ item for key, item in table.items() if self.parent.serial_port.parity == key ] self.parity_combobox.setCurrentIndex(parity_values.index(xxx[0])) else: self.parity_combobox.setCurrentIndex( self.parity_combobox.findText("None")) self.parity_combobox.setDisabled(True) self.flowcontrol_combobox = QComboBox() for fc in flow_control_values: self.flowcontrol_combobox.addItem(str(fc)) if self.boolean_config_is_ok: if self.parent.serial_port.xonxoff: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("XON/XOFF")) elif self.parent.serial_port.rtscts: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("RTS/CTS")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) self.flowcontrol_combobox.setDisabled(True) self.nickname_lineedit = QLineEdit() if self.settings_parser.has_option('default', 'nickname'): nickname = self.settings_parser.get('default', 'nickname') if type(nickname) == str: nickname = nickname.decode('utf-8') self.nickname_lineedit.setText( self.settings_parser.get('default', 'nickname')) else: if self.parent.nickname is None: self.nickname_lineedit.setText("Guest_" + MD5.new( str(datetime.datetime.now())).digest().encode('hex')[:5]) else: self.nickname_lineedit.setText(self.parent.nickname) self.save_folder_editline = QLineEdit(self.parent.default_save_folder) self.save_folder_editline.editingFinished.connect( self.check_if_folder_exists) if self.settings_parser.has_option('default', 'default_save_folder'): folder = self.settings_parser.get('default', 'default_save_folder') if type(folder) == str: folder = folder.decode('utf-8') self.save_folder_editline.setText(folder) self.check_if_folder_exists() self.dir_browser_button = QPushButton() self.dir_browser_button.setIcon(QIcon(icons_folder + 'folder.png')) self.dir_browser_button.clicked.connect(self.choose_save_dir) self.horizontal_box_hboxlayout = QHBoxLayout() self.horizontal_box_hboxlayout.addWidget(self.save_folder_editline) self.horizontal_box_hboxlayout.addWidget(self.dir_browser_button) self.horizontal_box_container_widget = QWidget() self.horizontal_box_container_widget.setLayout( self.horizontal_box_hboxlayout) self.enable_ACP127 = QCheckBox() self.enable_ACP127.stateChanged.connect( self.enable_functionality_ACP127) if self.parent.acp127: self.enable_ACP127.setChecked(True) self.encryption_password_lineedit = QLineEdit() self.enable_encryption_checkbox = QCheckBox() self.enable_encryption_checkbox.stateChanged.connect( self.enable_functionality_encryption) if self.parent.isEncryptionEnabled: self.enable_encryption_checkbox.setChecked(True) self.encryption_password_lineedit.setEchoMode( QLineEdit.EchoMode.PasswordEchoOnEdit) if self.parent.encryption_key is not None: self.encryption_password_lineedit.setText( self.parent.encryption_key) if self.enable_encryption_checkbox.isChecked(): self.encryption_password_lineedit.setDisabled(False) else: self.encryption_password_lineedit.setDisabled(True) self.grid_form_layout = QFormLayout() self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_TITLE + ":", self.serial_dropdown) self.grid_form_layout.addRow(FORMLAYOUT_PROFILE_TITLE + ":", self.profiles_combobox) self.grid_form_layout.addRow(FORMLAYOUT_CUSTOM_SERIAL_SETTINGS_TITLE, self.custom_settings_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_INTERVAL_TIME_TITLE + ":", self.interval_time_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_SPEED_TITLE + "(baud):", self.serial_speed_combobox) self.grid_form_layout.addRow(FORMLAYOUT_DATA_BITS_TITLE + ":", self.databits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_STOP_BITS_TITLE + ":", self.stopbits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_PARITY_TITLE + ":", self.parity_combobox) self.grid_form_layout.addRow(FORMLAYOUT_FLOWCONTROL_TITLE + ":", self.flowcontrol_combobox) self.grid_form_layout.addRow( FORMLAYOUT_ENABLE_ACP127_TITLE + " ACP-127", self.enable_ACP127) self.grid_form_layout.addRow(FORMLAYOUT_ENABLE_ENCRYPTION_TITLE, self.enable_encryption_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_ENCRYPTION_KEY_TITLE, self.encryption_password_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_NICKNAME_TITLE + ":", self.nickname_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SAVE_FOLDER_FILE_TITLE + ":", self.horizontal_box_container_widget) self.grid_form_layout.addRow("", self.button_box_dialog) self.setLayout(self.grid_form_layout) self.show() def enable_functionality_encryption(self): if self.enable_encryption_checkbox.isChecked(): self.encryption_password_lineedit.setDisabled(False) else: self.encryption_password_lineedit.setDisabled(True) def check_if_folder_exists(self): if not os.path.isdir(self.save_folder_editline.text()): msgBox = QMessageBox(icon=QMessageBox.Warning, text=ERROR_NO_DIR_MESSAGE) msgBox.setWindowTitle(ERROR_NO_DIR_TITLE) msgBox.exec_() self.save_folder_editline.setText(self.parent.default_save_folder) def check_if_digit(self): try: int(self.interval_time_lineedit.text()) except: msgBox = QMessageBox(icon=QMessageBox.Warning, text=ERROR_NO_INT_MESSAGE) msgBox.setWindowTitle(ERROR_NO_INT_TITLE) msgBox.exec_() self.interval_time_lineedit.setText(str(self.parent.interval_time)) def choose_save_dir(self): fname = QFileDialog(self, FILEBROWSER_SAVE_FOLDER_TITLE) fname.setFileMode(QFileDialog.Directory) looking_label = QFileDialog.DialogLabel(QFileDialog.LookIn) filename_label = QFileDialog.DialogLabel(QFileDialog.FileName) filetype_label = QFileDialog.DialogLabel(QFileDialog.FileType) fname.setLabelText(looking_label, FILEBROWSER_SAVE_FOLDER_LOOKIN) fname.setLabelText(filename_label, FILEBROWSER_SAVE_FOLDER_FOLDERNAME) fname.setLabelText(filetype_label, FILEBROWSER_SAVE_FOLDER_FOLDERTYPE) fname.setOption(QFileDialog.ShowDirsOnly) if fname.exec_(): filename = fname.selectedFiles()[0] self.save_folder_editline.setText(filename) def enable_functionality_ACP127(self): if self.enable_ACP127.isChecked(): self.parent.acp127 = True else: self.parent.acp127 = False def apply_setting_changes(self): res = None self.parent.custom_settings_enable_disable = self.custom_settings_checkbox.isChecked( ) self.parent.choosen_profile = self.profiles_combobox.currentText() if self.parent.custom_settings_enable_disable: self.parent.choosen_profile = "Custom" if self.enable_encryption_checkbox.isChecked(): self.parent.isEncryptionEnabled = True self.parent.encryption_key = self.encryption_password_lineedit.text( ) else: self.parent.isEncryptionEnabled = False self.parent.encryption_key = None if self.nickname_lineedit.text() != "": nick = self.nickname_lineedit.text().rstrip() nick = nick.replace(" ", "_") self.parent.nickname = nick if self.save_folder_editline.text() != "": if os.path.isdir(self.save_folder_editline.text()): self.parent.default_save_folder = self.save_folder_editline.text( ) self.parent.interval_time = int(self.interval_time_lineedit.text()) if self.flowcontrol_combobox.currentText() == "XON/XOFF": x_control = True else: x_control = False if self.flowcontrol_combobox.currentText() == "RTS/CTS": r_control = True else: r_control = False if self.parent.receive is None: res = self.lib.set_serial( port=self.serial_dropdown.currentText(), baudrate=self.serial_speed_combobox.currentText(), bytesize=self.databits_combobox.currentText(), stopbits=self.stopbits_combobox.currentText(), parity=self.parity_combobox.currentText(), xonxoff=x_control, rtscts=r_control) else: self.parent.receive.loop_run = False self.parent.receive.wait() self.parent.receive = None res = self.lib.set_serial( port=self.serial_dropdown.currentText(), baudrate=self.serial_speed_combobox.currentText(), bytesize=self.databits_combobox.currentText(), stopbits=self.stopbits_combobox.currentText(), parity=self.parity_combobox.currentText(), xonxoff=x_control, rtscts=r_control) if type(res) == OSError: self.parent.status_bar_widget.showMessage(str(res), 5000) msgBox = QMessageBox(icon=QMessageBox.Critical, text=str(res)) msgBox.setWindowTitle(ERROR_INTERFACE_TITLE) msgBox.exec_() if type(res) is not None and type(res) != OSError: self.parent.serial_port = res self.parent.start_threads() self.parent.status_bar_widget.showMessage( MSG_SERIAL_INT_STARTED % self.parent.serial_port.port) def change_custom_settings_on_profile(self): if self.profiles_combobox.currentText() != 'None': section = self.profiles_combobox.currentText() self.interval_time_lineedit.setText( self.config_parser.get(section, "interval")) self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText( self.config_parser.get(section, "serialspeed"))) self.databits_combobox.setCurrentIndex( self.databits_combobox.findText( self.config_parser.get(section, "bytesize"))) self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText( self.config_parser.get(section, "stopbits"))) self.parity_combobox.setCurrentIndex( self.parity_combobox.findText( self.config_parser.get(section, "parity"))) if self.config_parser.get(section, "xonxoff") == 'True': self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("XON/XOFF")) elif self.config_parser.get(section, "rtscts") == 'True': self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("RTS/CTS")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) if self.config_parser.get(section, "acp127") == "True": self.enable_ACP127.setChecked(True) else: self.enable_ACP127.setChecked(False) elif self.profiles_combobox.currentText() == "None": self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText('9600')) self.interval_time_lineedit.setText(str(self.parent.intervaltime)) self.databits_combobox.setCurrentIndex( self.databits_combobox.findText('8')) self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText('1')) self.parity_combobox.setCurrentIndex( self.parity_combobox.findText('None')) self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText('None')) self.enable_ACP127.setChecked(False) def custom_settings_enable_disable(self): if self.custom_settings_checkbox.isChecked(): self.interval_time_lineedit.setDisabled(False) self.serial_speed_combobox.setDisabled(False) self.databits_combobox.setDisabled(False) self.stopbits_combobox.setDisabled(False) self.parity_combobox.setDisabled(False) self.flowcontrol_combobox.setDisabled(False) else: self.interval_time_lineedit.setDisabled(True) self.serial_speed_combobox.setDisabled(True) self.databits_combobox.setDisabled(True) self.stopbits_combobox.setDisabled(True) self.parity_combobox.setDisabled(True) self.flowcontrol_combobox.setDisabled(True)
def createWidgets(self): self.formatPanel = Widgets.FormatPanel.Panel(self.state, self, editableFontSize=True) formatActions = self.formatPanel.formatActions self.titleLabel = QLabel("&Index Title") self.titleTextEdit = Widgets.LineEdit.HtmlLineEdit( self.state, formatActions=formatActions) self.titleLabel.setBuddy(self.titleTextEdit) self.titleTextEdit.setHtml(self.config.get(Gconf.Key.Title)) self.form.tooltips.append((self.titleTextEdit, """\ <p><b>Index Title</b></p> <p>The index's title. Leave blank if the title is to be added directly in the output file.</p>""")) self.noteLabel = QLabel("Index &Note") self.noteTextEdit = Widgets.LineEdit.MultilineHtmlEdit( self.state, maxLines=8, formatActions=formatActions) self.noteLabel.setBuddy(self.noteTextEdit) self.noteTextEdit.setLineWrapMode(QTextEdit.FixedColumnWidth) self.noteTextEdit.setLineWrapColumnOrWidth(60) self.noteTextEdit.setWordWrapMode(QTextOption.WordWrap) self.noteTextEdit.setHtml(self.config.get(Gconf.Key.Note)) self.form.tooltips.append((self.noteTextEdit, """\ <p><b>Index Note</b></p> <p>The index's note. Leave blank if no note is required or if the note is to be added directly in the output file.</p>""")) self.sectionsGroupBox = QGroupBox("Sections") self.blankBeforeLabel = QLabel("&Blank Lines Before") self.blankBeforeSpinBox = QSpinBox() self.blankBeforeSpinBox.setAlignment(Qt.AlignRight) self.blankBeforeLabel.setBuddy(self.blankBeforeSpinBox) self.blankBeforeSpinBox.setRange(0, 3) self.blankBeforeSpinBox.setValue( self.config.get(Gconf.Key.SectionPreLines)) self.form.tooltips.append((self.blankBeforeSpinBox, """\ <p><b>Blank Lines Before</b></p> <p>How many blank lines to output before a section. (A section is a distinct part of the index, e.g., the ‘A’s.)</p>""")) self.blankAfterLabel = QLabel("Blank &Lines After") self.blankAfterSpinBox = QSpinBox() self.blankAfterSpinBox.setAlignment(Qt.AlignRight) self.blankAfterLabel.setBuddy(self.blankAfterSpinBox) self.blankAfterSpinBox.setRange(0, 3) self.blankAfterSpinBox.setValue( self.config.get(Gconf.Key.SectionPostLines)) self.form.tooltips.append((self.blankAfterSpinBox, """\ <p><b>Blank Lines After</b></p> <p>How many blank lines to output before after section's title. (A section is a distinct part of the index, e.g., the ‘A’s.)</p>""")) self.sectionTitlesCheckBox = QCheckBox("&Output Titles") self.sectionTitlesCheckBox.setChecked( self.config.get(Gconf.Key.SectionTitles)) self.form.tooltips.append((self.sectionTitlesCheckBox, """\ <p><b>Output Titles</b></p> <p>If checked, section titles are output before each section, e.g., ‘A’, before the As, ‘B’, before the Bs, and so on.</p>""")) self.sectionSpecialTitleLabel = QLabel("Special Section &Title") self.sectionSpecialTitleTextEdit = Widgets.LineEdit.HtmlLineEdit( self.state, formatActions=formatActions) self.sectionSpecialTitleLabel.setBuddy( self.sectionSpecialTitleTextEdit) self.sectionSpecialTitleTextEdit.setHtml( self.config.get(Gconf.Key.SectionSpecialTitle)) self.form.tooltips.append((self.sectionSpecialTitleTextEdit, """\ <p><b>Special Section Title</b></p> <p>If there are entries which precede the ‘A’ section, then this section title will be used for them.</p> <p>Note that even if this title isn't used, its font name and size will be used for all the other section titles.</p>""")) size = self.font().pointSize() + (1 if WIN else 2) family = self.config.get(Gconf.Key.StdFont) size = self.config.get(Gconf.Key.StdFontSize, size) Lib.createFontBoxesFor(self, "Std", family, size, tooltips=self.form.tooltips, which="Std.") self.onStdFontChange(False) family = self.config.get(Gconf.Key.AltFont) size = self.config.get(Gconf.Key.AltFontSize, size) Lib.createFontBoxesFor(self, "Alt", family, size, tooltips=self.form.tooltips, which="Alt.") self.onAltFontChange(False) family = self.config.get(Gconf.Key.MonoFont) size = self.config.get(Gconf.Key.MonoFontSize, size) Lib.createFontBoxesFor(self, "Mono", family, size, mono=True, tooltips=self.form.tooltips, which="Mono.") self.onMonoFontChange(False) self.monoFontAsStrikeoutCheckbox = QCheckBox( "Output Mono. &Font as Strikeout") self.form.tooltips.append((self.monoFontAsStrikeoutCheckbox, """\ <p><b>Output Mono. Font as Strikeout</b></p> <p>If checked, any text in the index that is styled as mono. font family will be output using the std. font family—but with <s>strikeout</s>.</p>""")) self.monoFontAsStrikeoutCheckbox.setChecked( self.config.get(Gconf.Key.MonoFontAsStrikeout)) self.styleLabel = QLabel("St&yle") self.styleComboBox = QComboBox() self.styleLabel.setBuddy(self.styleComboBox) oldStyle = self.config.get(Gconf.Key.Style) index = -1 for i, style in enumerate(StyleKind): self.styleComboBox.addItem(style.text, style.value) if style is oldStyle: index = i self.styleComboBox.setCurrentIndex(index) self.form.tooltips.append((self.styleComboBox, """\ <p><b>Style</b></p> <p>The style of index to output.</p>""")) self.termPagesSepLabel = QLabel("T&erm-Pages Separator") self.termPagesSepTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit( self.state, 3, formatActions=formatActions) self.termPagesSepLabel.setBuddy(self.termPagesSepTextEdit) self.termPagesSepTextEdit.setHtml( self.config.get(Gconf.Key.TermPagesSeparator)) self.form.tooltips.append((self.termPagesSepTextEdit, """\ <p><b>Term-Pages Separator</b></p> <p>The separator text to use between the end of an entry's term and its pages.</p>{}""".format(BLANK_SPACE_HTML))) self.runInSepLabel = QLabel("&Run-in Separator") self.runInSepTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit( self.state, 3, formatActions=formatActions) self.runInSepLabel.setBuddy(self.runInSepTextEdit) self.runInSepTextEdit.setHtml(self.config.get( Gconf.Key.RunInSeparator)) self.form.tooltips.append((self.runInSepTextEdit, """\ <p><b>Run-in Separator</b></p> <p>The separator text to use between run-in entries (for run-in style index output).</p>{}""".format(BLANK_SPACE_HTML))) self.formatPanel.state.editors = [ self.titleTextEdit, self.noteTextEdit, self.sectionSpecialTitleTextEdit, self.termPagesSepTextEdit, self.runInSepTextEdit ]
class SceneTab(QWidget): #FIXME I'm Ugly. """This widget is for changing the Scene propagation policies of the module. """ def __init__(self, parent, agent): """Construct the SceneTab with the given parent (TabDialog) and ModuleAgent. """ super(SceneTab, self).__init__(parent) self.agent = agent self.layout = QVBoxLayout() self.layout.setAlignment(Qt.AlignCenter) self.layout.addWidget(self.buildHighlightGroupBox()) self.layout.addItem(QSpacerItem(5, 5)) self.layout.addWidget(self.buildModuleGroupBox()) self.layout.addItem(QSpacerItem(5, 5)) self.layout.addWidget(self.buildAttributeGroupBox()) self.setLayout(self.layout) def buildHighlightGroupBox(self): """Layout/construct the highlight UI for this tab.""" groupBox = QGroupBox("Highlight Policy") layout = QVBoxLayout() # agent.propagate_highlights self.highlights_propagate = QCheckBox("Propagate highlights to " + "other modules.") self.highlights_propagate.setChecked(self.agent.propagate_highlights) self.highlights_propagate.stateChanged.connect( self.highlightsPropagateChanged) # We only allow this change if the parent does not propagate if self.agent.parent().propagate_highlights: self.highlights_propagate.setDisabled(True) # agent.apply_highlights self.applyHighlights = QCheckBox("Apply highlights from " + "other modules.") self.applyHighlights.setChecked(self.agent.apply_highlights) self.applyHighlights.stateChanged.connect(self.applyHighlightsChanged) layout.addWidget(self.applyHighlights) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.highlights_propagate) groupBox.setLayout(layout) return groupBox def highlightsPropagateChanged(self): """Called when highlight propagtion is changed to update the Agent. """ self.agent.propagate_highlights = self.highlights_propagate.isChecked() def applyHighlightsChanged(self): """Called when highlight application is changed to update the Agent. """ self.agent.apply_highlights = self.applyHighlights.isChecked() def buildModuleGroupBox(self): """Layout/construct the ModuleScene UI for this tab.""" groupBox = QGroupBox("Module Policy") layout = QVBoxLayout() # agent.propagate_module_scenes self.module_propagate = QCheckBox( "Propagate module scene information " + "to other modules.") self.module_propagate.setChecked(self.agent.propagate_module_scenes) self.module_propagate.stateChanged.connect(self.modulePropagateChanged) # We only allow this change if the parent does not propagate if self.agent.parent().propagate_module_scenes: self.module_propagate.setDisabled(True) # agent.apply_module_scenes self.module_applyScene = QCheckBox("Apply module scene information " + "from other modules.") self.module_applyScene.setChecked(self.agent.apply_module_scenes) self.module_applyScene.stateChanged.connect(self.moduleApplyChanged) layout.addWidget(self.module_applyScene) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.module_propagate) groupBox.setLayout(layout) return groupBox def modulePropagateChanged(self): """Called when ModuleScene propagtion is changed to update the Agent. """ self.agent.propagate_module_scenes = self.module_propagate.isChecked() def moduleApplyChanged(self): """Called when ModuleScene application is changed to update the Agent. """ self.agent.apply_module_scenes = self.module_applyScene.isChecked() def buildAttributeGroupBox(self): """Layout/construct the AttributeScene UI for this tab.""" groupBox = QGroupBox("Attribute Policy (Colors)") layout = QVBoxLayout() # agent.propagate_attribute_scenes self.attr_propagate = QCheckBox( "Propagate attribute scene " + "information (e.g. color maps) to other modules.") self.attr_propagate.setChecked(self.agent.propagate_attribute_scenes) self.attr_propagate.stateChanged.connect(self.attrPropagateChanged) # We only allow this change if the parent does not propagate if self.agent.parent().propagate_attribute_scenes: self.attr_propagate.setDisabled(True) # agent.apply_attribute_scenes self.attr_applyScene = QCheckBox("Apply attribute scene information " + "from other modules.") self.attr_applyScene.setChecked(self.agent.apply_attribute_scenes) self.attr_applyScene.stateChanged.connect(self.attrApplyChanged) layout.addWidget(self.attr_applyScene) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.attr_propagate) groupBox.setLayout(layout) return groupBox def attrPropagateChanged(self): """Called when AttributeScene propagtion is changed to update the Agent. """ self.agent.propagate_attribute_scenes = self.attr_propagate.isChecked() def attrApplyChanged(self): """Called when AttributeScene application is changed to update the Agent. """ self.agent.apply_attribute_scenes = self.attr_applyScene.isChecked()
def __init__(self, *args, **kwargs): self.get_csv_form_google_spreadsheets(Widget_FileTree.url, Widget_FileTree.csv) self.dict_extensionList = self.get_dictList_from_csvPath( Widget_FileTree.csv) super(Widget_FileTree, self).__init__(*args, **kwargs) self.installEventFilter(self) mainLayout = QVBoxLayout(self) mainLayout.setContentsMargins(0, 5, 0, 0) w_basePath = QWidget() lay_basePath = QHBoxLayout(w_basePath) w_basePath.setStyleSheet("font-size:12px") lay_basePath.setContentsMargins(5, 0, 3, 0) label_basePath = QLabel("Base Path : ") lineEdit_basePath = QLineEdit() lineEdit_basePath.setMinimumHeight(22) lineEdit_basePath.setReadOnly(True) lay_basePath.addWidget(label_basePath) lay_basePath.addWidget(lineEdit_basePath) w_tree = QTreeWidget() w_tree.setColumnCount(2) headerItem = w_tree.headerItem() headerItem.setText(0, "File Path") headerItem.setText(1, "Target Node") w_tree.itemExpanded.connect(self.setContentsWidth) w_tree.itemCollapsed.connect(self.setContentsWidth) w_tree.setSelectionMode(QAbstractItemView.ExtendedSelection) self.w_typeAttrList = Widget_TypeAttributeList() w_tree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) QtCore.QObject.connect( w_tree, QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.loadContextMenu) w_check = QWidget() lay_check = QHBoxLayout(w_check) lay_check.setContentsMargins(5, 5, 0, 10) lay_check.setSpacing(0) checkBox = QCheckBox() checkBox.setFixedWidth(30) label = QLabel("Show Unused files in folder") label.setStyleSheet("font-size:12px") lay_check.addWidget(checkBox) lay_check.addWidget(label) mainLayout.addWidget(w_basePath) mainLayout.addWidget(w_tree) mainLayout.addWidget(w_check) self.w_tree = w_tree self.checkBox = checkBox self.lineEdit = lineEdit_basePath self.load_checkBoxValue(checkBox, Widget_FileTree.path_uiInfo) QtCore.QObject.connect(checkBox, QtCore.SIGNAL("stateChanged(int)"), self.saveCheckBoxValue) QtCore.QObject.connect(w_tree, QtCore.SIGNAL("itemSelectionChanged()"), self.selectItem)
class QLogger(logging.Handler): '''Code from: https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt ''' def __init__(self, parent=None, format=settings.log_fmt, level=logging.INFO): logging.Handler.__init__(self) # Initialize a log handler as the super class self.setFormatter(logging.Formatter(format)) # Set the formatter for the logger self.setLevel(level) # Set the logging level self.frame = QFrame(parent) # Initialize a QFrame to place other widgets in self.frame2 = QFrame(parent) # Initialize frame2 for the label and checkbox self.label = QLabel('Logs') # Define a label for the frame self.check = QCheckBox('Debugging') # Checkbox to enable debugging logging self.check.clicked.connect(self.__changeLevel) # Connect checkbox clicked to the __changeLevel method self.log_widget = QTextEdit() # Initialize a QPlainTextWidget to write logs to self.log_widget.verticalScrollBar().minimum() # Set a vertical scroll bar on the log widget self.log_widget.horizontalScrollBar().minimum() # Set a horizontal scroll bar on the log widget self.log_widget.setLineWrapMode(self.log_widget.NoWrap) # Set line wrap mode to no wrapping self.log_widget.setFont(QFont("Courier", 12)) # Set the font to a monospaced font self.log_widget.setReadOnly(True) # Set log widget to read only layout = QHBoxLayout() # Initialize a horizontal layout scheme for the label and checkbox frame layout.addWidget(self.label) # Add the label to the layout scheme layout.addWidget(self.check) # Add the checkbox to the layout scheme self.frame2.setLayout(layout) # Set the layout for frame to the horizontal layout layout = QVBoxLayout() # Initialize a layout scheme for the widgets layout.addWidget(self.frame2) # Add the label/checkbox frame to the layout scheme layout.addWidget(self.log_widget) # Add the text widget to the layout scheme self.frame.setLayout(layout) # Set the layout of the fram to the layout scheme defined ############################################################################## def emit(self, record): ''' Overload the emit method so that it prints to the text widget ''' msg = self.format(record) # Format the message for logging if record.levelno >= logging.CRITICAL: # If the log level is critical self.log_widget.setTextColor(Qt.red) # Set text color to red elif record.levelno >= logging.ERROR: # Elif level is error self.log_widget.setTextColor(Qt.darkMagenta) # Set text color to darkMagenta elif record.levelno >= logging.WARNING: # Elif level is warning self.log_widget.setTextColor(Qt.darkCyan) # Set text color to darkCyan else: # Else self.log_widget.setTextColor(Qt.black) # Set text color to black self.log_widget.append(msg) # Add the log to the text widget ############################################################################## def write(self, m): ''' Overload the write method so that it does nothing ''' pass ############################################################################## def __changeLevel(self, *args): ''' Private method to change logging level ''' if self.check.isChecked(): self.setLevel(logging.DEBUG) # Get the Meso1819 root logger and add the handler to it else: self.setLevel(logging.INFO)
def __init__(self, parent=None): super(RobocompDslGui, self).__init__(parent) self.setWindowTitle("Create new component") # self._idsl_paths = [] self._communications = { "implements": [], "requires": [], "subscribesTo": [], "publishes": [] } self._interfaces = {} self._cdsl_doc = CDSLDocument() self._command_process = QProcess() self._main_widget = QWidget() self._main_layout = QVBoxLayout() self.setCentralWidget(self._main_widget) self._name_layout = QHBoxLayout() self._name_line_edit = QLineEdit() self._name_line_edit.textEdited.connect(self.update_component_name) self._name_line_edit.setPlaceholderText("New component name") self._name_layout.addWidget(self._name_line_edit) self._name_layout.addStretch() # DIRECTORY SELECTION self._dir_line_edit = QLineEdit() # self._dir_line_edit.textEdited.connect(self.update_completer) self._dir_completer = QCompleter() self._dir_completer_model = QFileSystemModel() if os.path.isdir(ROBOCOMP_COMP_DIR): self._dir_line_edit.setText(ROBOCOMP_COMP_DIR) self._dir_completer_model.setRootPath(ROBOCOMP_COMP_DIR) self._dir_completer.setModel(self._dir_completer_model) self._dir_line_edit.setCompleter(self._dir_completer) self._dir_button = QPushButton("Select directory") self._dir_button.clicked.connect(self.set_output_directory) self._dir_layout = QHBoxLayout() self._dir_layout.addWidget(self._dir_line_edit) self._dir_layout.addWidget(self._dir_button) # LIST OF ROBOCOMP INTERFACES self._interface_list = QListWidget() self._interface_list.setSelectionMode( QAbstractItemView.ExtendedSelection) self._interface_list.itemSelectionChanged.connect( self.set_comunication) # LIST OF CONNECTION TyPES self._type_combo_box = QComboBox() self._type_combo_box.addItems( ["publishes", "implements", "subscribesTo", "requires"]) self._type_combo_box.currentIndexChanged.connect( self.reselect_existing) # BUTTON TO ADD A NEW CONNECTION # self._add_connection_button = QPushButton("Add") # self._add_connection_button.clicked.connect(self.add_new_comunication) self._add_connection_layout = QHBoxLayout() # self._add_connection_layout.addWidget(self._add_connection_button) self._language_combo_box = QComboBox() self._language_combo_box.addItems(["Python", "Cpp", "Cpp11"]) self._language_combo_box.currentIndexChanged.connect( self.update_language) self._add_connection_layout.addWidget(self._language_combo_box) self._add_connection_layout.addStretch() self._gui_check_box = QCheckBox() self._gui_check_box.stateChanged.connect(self.update_gui_selection) self._gui_label = QLabel("Use Qt GUI") self._add_connection_layout.addWidget(self._gui_label) self._add_connection_layout.addWidget(self._gui_check_box) # WIDGET CONTAINING INTERFACES AND TYPES self._selection_layout = QVBoxLayout() self._selection_layout.addWidget(self._type_combo_box) self._selection_layout.addWidget(self._interface_list) self._selection_layout.addLayout(self._add_connection_layout) self._selection_widget = QWidget() self._selection_widget.setLayout(self._selection_layout) # TEXT EDITOR WITH THE RESULTING CDSL CODE self._editor = QTextEdit(self) self._editor.setHtml("") self._document = self._editor.document() self._component_directory = None # SPLITTER WITH THE SELECTION AND THE CODE self._body_splitter = QSplitter(Qt.Horizontal) self._body_splitter.addWidget(self._selection_widget) self._body_splitter.addWidget(self._editor) self._body_splitter.setStretchFactor(0, 2) self._body_splitter.setStretchFactor(1, 9) # CREATION BUTTONS self._create_button = QPushButton("Create .cdsl") self._create_button.clicked.connect(self.write_cdsl_file) self._creation_layout = QHBoxLayout() self._creation_layout.addStretch() self._creation_layout.addWidget(self._create_button) self._console = QConsole() self._command_process.readyReadStandardOutput.connect( self._console.standard_output) self._command_process.readyReadStandardError.connect( self._console.error_output) # ADDING WIDGETS TO MAIN LAYOUT self._main_widget.setLayout(self._main_layout) self._main_layout.addLayout(self._name_layout) self._main_layout.addLayout(self._dir_layout) self._main_layout.addWidget(self._body_splitter) self._main_layout.addLayout(self._creation_layout) self._main_layout.addWidget(self._console) self.setMinimumSize(800, 500) self._editor.setText(self._cdsl_doc.generate_doc())
class RobocompDslGui(QMainWindow): def __init__(self, parent=None): super(RobocompDslGui, self).__init__(parent) self.setWindowTitle("Create new component") # self._idsl_paths = [] self._communications = { "implements": [], "requires": [], "subscribesTo": [], "publishes": [] } self._interfaces = {} self._cdsl_doc = CDSLDocument() self._command_process = QProcess() self._main_widget = QWidget() self._main_layout = QVBoxLayout() self.setCentralWidget(self._main_widget) self._name_layout = QHBoxLayout() self._name_line_edit = QLineEdit() self._name_line_edit.textEdited.connect(self.update_component_name) self._name_line_edit.setPlaceholderText("New component name") self._name_layout.addWidget(self._name_line_edit) self._name_layout.addStretch() # DIRECTORY SELECTION self._dir_line_edit = QLineEdit() # self._dir_line_edit.textEdited.connect(self.update_completer) self._dir_completer = QCompleter() self._dir_completer_model = QFileSystemModel() if os.path.isdir(ROBOCOMP_COMP_DIR): self._dir_line_edit.setText(ROBOCOMP_COMP_DIR) self._dir_completer_model.setRootPath(ROBOCOMP_COMP_DIR) self._dir_completer.setModel(self._dir_completer_model) self._dir_line_edit.setCompleter(self._dir_completer) self._dir_button = QPushButton("Select directory") self._dir_button.clicked.connect(self.set_output_directory) self._dir_layout = QHBoxLayout() self._dir_layout.addWidget(self._dir_line_edit) self._dir_layout.addWidget(self._dir_button) # LIST OF ROBOCOMP INTERFACES self._interface_list = QListWidget() self._interface_list.setSelectionMode( QAbstractItemView.ExtendedSelection) self._interface_list.itemSelectionChanged.connect( self.set_comunication) # LIST OF CONNECTION TyPES self._type_combo_box = QComboBox() self._type_combo_box.addItems( ["publishes", "implements", "subscribesTo", "requires"]) self._type_combo_box.currentIndexChanged.connect( self.reselect_existing) # BUTTON TO ADD A NEW CONNECTION # self._add_connection_button = QPushButton("Add") # self._add_connection_button.clicked.connect(self.add_new_comunication) self._add_connection_layout = QHBoxLayout() # self._add_connection_layout.addWidget(self._add_connection_button) self._language_combo_box = QComboBox() self._language_combo_box.addItems(["Python", "Cpp", "Cpp11"]) self._language_combo_box.currentIndexChanged.connect( self.update_language) self._add_connection_layout.addWidget(self._language_combo_box) self._add_connection_layout.addStretch() self._gui_check_box = QCheckBox() self._gui_check_box.stateChanged.connect(self.update_gui_selection) self._gui_label = QLabel("Use Qt GUI") self._add_connection_layout.addWidget(self._gui_label) self._add_connection_layout.addWidget(self._gui_check_box) # WIDGET CONTAINING INTERFACES AND TYPES self._selection_layout = QVBoxLayout() self._selection_layout.addWidget(self._type_combo_box) self._selection_layout.addWidget(self._interface_list) self._selection_layout.addLayout(self._add_connection_layout) self._selection_widget = QWidget() self._selection_widget.setLayout(self._selection_layout) # TEXT EDITOR WITH THE RESULTING CDSL CODE self._editor = QTextEdit(self) self._editor.setHtml("") self._document = self._editor.document() self._component_directory = None # SPLITTER WITH THE SELECTION AND THE CODE self._body_splitter = QSplitter(Qt.Horizontal) self._body_splitter.addWidget(self._selection_widget) self._body_splitter.addWidget(self._editor) self._body_splitter.setStretchFactor(0, 2) self._body_splitter.setStretchFactor(1, 9) # CREATION BUTTONS self._create_button = QPushButton("Create .cdsl") self._create_button.clicked.connect(self.write_cdsl_file) self._creation_layout = QHBoxLayout() self._creation_layout.addStretch() self._creation_layout.addWidget(self._create_button) self._console = QConsole() self._command_process.readyReadStandardOutput.connect( self._console.standard_output) self._command_process.readyReadStandardError.connect( self._console.error_output) # ADDING WIDGETS TO MAIN LAYOUT self._main_widget.setLayout(self._main_layout) self._main_layout.addLayout(self._name_layout) self._main_layout.addLayout(self._dir_layout) self._main_layout.addWidget(self._body_splitter) self._main_layout.addLayout(self._creation_layout) self._main_layout.addWidget(self._console) self.setMinimumSize(800, 500) self._editor.setText(self._cdsl_doc.generate_doc()) # self.editor->show(); # def update_completer(self, path): # print "update_completer %s"%path # info = QFileInfo(path) # if info.exists() and info.isDir(): # if not path.endswith(os.path.pathsep): # new_path = os.path.join(path, os.sep) # # self._dir_line_edit.setText(new_path) # all_dirs_output = [dI for dI in os.listdir(path) if os.path.isdir(os.path.join(path, dI))] # print all_dirs_output # self._dir_completer.complete() def load_idsl_files(self, fullpath=None): if fullpath is None: fullpath = ROBOCOMP_INTERFACES idsls_dir = os.path.join(ROBOCOMP_INTERFACES, "IDSLs") if os.path.isdir(idsls_dir): for full_filename in os.listdir(idsls_dir): file_name, file_extension = os.path.splitext(full_filename) if "idsl" in file_extension.lower(): full_idsl_path = os.path.join(idsls_dir, full_filename) # self._idsl_paths.append(os.path.join(idsls_dir,full_filename)) self.parse_idsl_file(full_idsl_path) self._interface_list.addItems(self._interfaces.keys()) def parse_idsl_file(self, fullpath): with open(fullpath, 'r') as fin: interface_name = None for line in fin: result = re.findall(r'^\s*interface\s+(\w+)\s*\{?\s*$', line, flags=re.MULTILINE) if len(result) > 0: interface_name = result[0] print("%s for idsl %s" % (interface_name, fullpath)) if interface_name is not None: self._interfaces[interface_name] = fullpath def add_new_comunication(self): interface_names = self._interface_list.selectedItems() com_type = str(self._type_combo_box.currentText()) for iface_name_item in interface_names: iface_name = str(iface_name_item.text()) self._communications[com_type].append(iface_name) idsl_full_path = self._interfaces[iface_name] idsl_full_filename = os.path.basename(idsl_full_path) self._cdsl_doc.add_comunication(com_type, iface_name) self._cdsl_doc.add_import(idsl_full_filename) self.update_editor() def set_comunication(self): interface_names = self._interface_list.selectedItems() com_type = str(self._type_combo_box.currentText()) self._communications[com_type] = [] self._cdsl_doc.clear_comunication(com_type) for iface_name_item in interface_names: iface_name = str(iface_name_item.text()) self._communications[com_type].append(iface_name) self._cdsl_doc.add_comunication(com_type, iface_name) self.update_imports() self.update_editor() def update_imports(self): self._cdsl_doc.clear_imports() for com_type in self._communications: for iface_name in self._communications[com_type]: idsl_full_path = self._interfaces[iface_name] idsl_full_filename = os.path.basename(idsl_full_path) self._cdsl_doc.add_import(idsl_full_filename) def update_language(self): language = self._language_combo_box.currentText() self._cdsl_doc.set_language(str(language)) self.update_editor() def update_gui_selection(self): checked = self._gui_check_box.isChecked() if checked: self._cdsl_doc.set_qui(True) else: self._cdsl_doc.set_qui(False) self.update_editor() def update_component_name(self, name): self._cdsl_doc.set_name(name) self.update_editor() def update_editor(self): self._editor.setText(self._cdsl_doc.generate_doc()) def set_output_directory(self): dir_set = False while not dir_set: dir = QFileDialog.getExistingDirectory( self, "Select Directory", ROBOCOMP_COMP_DIR, QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) if self.check_dir_is_empty(str(dir)): self._dir_line_edit.setText(dir) dir_set = True def write_cdsl_file(self): component_dir = str(self._dir_line_edit.text()) text = self._cdsl_doc.generate_doc() if not self._name_line_edit.text(): component_name, ok = QInputDialog.getText(self, 'No component name set', 'Enter component name:') if ok: self.update_component_name(component_name) self._name_line_edit.setText(component_name) else: return False if not os.path.exists(component_dir): if QMessageBox.Yes == QMessageBox.question( self, "Directory doesn't exist.", "Do you want create the directory %s?" % component_dir, QMessageBox.Yes | QMessageBox.No): os.makedirs(component_dir) else: QMessageBox.question( self, "Directory not exist", "Can't create a component witout a valid directory") return False file_path = os.path.join(component_dir, str(self._name_line_edit.text()) + ".cdsl") if os.path.exists(file_path): if QMessageBox.No == QMessageBox.question( self, "File already exists", "Do you want to overwrite?", QMessageBox.Yes | QMessageBox.No): return False with open(file_path, 'w') as the_file: the_file.write(text) self.execute_robocomp_cdsl() return True def execute_robocomp_cdsl(self): cdsl_file_path = os.path.join( str(self._dir_line_edit.text()), str(self._name_line_edit.text()) + ".cdsl") command = "python -u %s/robocompdsl.py %s %s" % ( ROBOCOMPDSL_DIR, cdsl_file_path, os.path.join(str(self._dir_line_edit.text()))) self._console.append_custom_text("%s\n" % command) self._command_process.start(command, QProcess.Unbuffered | QProcess.ReadWrite) def reselect_existing(self): com_type = self._type_combo_box.currentText() selected = self._communications[com_type] self._interface_list.clearSelection() for iface in selected: items = self._interface_list.findItems(iface, Qt.MatchFlag.MatchExactly) if len(items) > 0: item = items[0] item.setSelected(True) def check_dir_is_empty(self, dir_path): if len(os.listdir(dir_path)) > 0: msgBox = QMessageBox() msgBox.setWindowTitle("Directory not empty") msgBox.setText( "The selected directory is not empty.\n" "For a new Component you usually want a new directory.\n" "Do you want to use this directory anyway?") msgBox.setStandardButtons(QMessageBox.Yes) msgBox.addButton(QMessageBox.No) msgBox.setDefaultButton(QMessageBox.No) if msgBox.exec_() == QMessageBox.Yes: return True else: return False else: return True
def createBinaryOptions(self): """ Binary Analysis Options """ groupBox = QtGui.QGroupBox('Binary Analysis') # Elements cbs_unique_str = QCheckBox('Show unique strings', self) cbs_unique_com = QCheckBox('Show unique comments', self) cbs_unique_calls = QCheckBox('Show unique calls', self) cbs_entropy = QCheckBox('Calculate entropy', self) cutoff_label = QLabel('Connect BB cutoff') sb_cutoff = QSpinBox() sb_cutoff.setRange(1, 40) cutoff_func_label = QLabel('Connect functions cutoff') sbf_cutoff = QSpinBox() sbf_cutoff.setRange(1, 40) # Default states are read from the Config # class and reflected in the GUI cbs_unique_str.setCheckState( self.get_state(self.config.display_unique_strings)) cbs_unique_com.setCheckState( self.get_state(self.config.display_unique_comments)) cbs_unique_calls.setCheckState( self.get_state(self.config.display_unique_calls)) cbs_entropy.setCheckState(self.get_state( self.config.calculate_entropy)) sb_cutoff.setValue(self.config.connect_bb_cutoff) sbf_cutoff.setValue(self.config.connect_func_cutoff) # Connect elements and signals cbs_unique_str.stateChanged.connect(self.string_unique) cbs_unique_com.stateChanged.connect(self.comment_unique) cbs_unique_calls.stateChanged.connect(self.calls_unique) cbs_entropy.stateChanged.connect(self.string_entropy) sb_cutoff.valueChanged[int].connect(self.set_cutoff) sb_cutoff.valueChanged[int].connect(self.set_func_cutoff) vbox = QtGui.QVBoxLayout() vbox.addWidget(cbs_unique_str) vbox.addWidget(cbs_unique_com) vbox.addWidget(cbs_unique_calls) vbox.addWidget(cbs_entropy) vbox.addWidget(cutoff_label) vbox.addWidget(sb_cutoff) vbox.addWidget(cutoff_func_label) vbox.addWidget(sbf_cutoff) vbox.addStretch(1) groupBox.setLayout(vbox) return groupBox
class EditConfigurationDialog(QDialog): def __init__(self, parent): global configuration super(EditConfigurationDialog, self).__init__(parent) title = _("Preferences") self.setWindowTitle(title) self.title_widget = TitleWidget(title, self) self.buttons = QDialogButtonBox() self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.font_select = QCheckBox() self.server_address = QLineEdit() form_layout = QFormLayout() form_layout.addRow(_("Fonts"), self.font_select) form_layout.addRow(_("Server's IP address"), self.server_address) top_layout = QVBoxLayout() top_layout.addWidget(self.title_widget) top_layout.addLayout(form_layout) top_layout.addWidget(self.buttons) self.setLayout(top_layout) # QWidget takes ownership of the layout self.buttons.accepted.connect(self.save_and_accept) self.buttons.rejected.connect(self.cancel) self._load_configuration(configuration) def _load_configuration(self, config): host_or_ip = "" if config: if config.get("DownloadSite", "base_url"): r = re.compile('https?://([^:]+):.*') host_or_ip = r.match(config.get("DownloadSite", "base_url")).groups()[0] elif config.database_url: r = re.compile('.*@([^:]+):.*') host_or_ip = r.match(config.database_url).groups()[0] self.server_address.setText(host_or_ip) self.font_select.setChecked(config.font_select) @Slot() def cancel(self): return super(EditConfigurationDialog, self).reject() @Slot() def save_and_accept(self): super(EditConfigurationDialog, self).accept() configuration.font_select = self.font_select.isChecked() configuration.set_server_network_address( self.server_address.text().strip(), overwrite=True) configuration.save() showWarningBox( _("Restart needed"), _("The modifications you have requested needs a restart of the application to be applied. They will take effect when you restart the application." )) self.deleteLater()
class ToolBox(QVBoxLayout): sig = QtCore.Signal(object) listThread = None groupBoxThreadInfo = None threadvbox = None mode = None def __init__(self, mode, parentQWidget=None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200, 30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100, 30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;" ) vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QtGui.QTableWidget(3, 2) self.tableTime.setHorizontalHeaderLabels(['-', 'time']) self.tableTime.setColumnWidth(0, 80) self.tableTime.setColumnWidth(1, 150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0, 0, QTableWidgetItem('begin')) self.tableTime.setItem(0, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(1, 0, QTableWidgetItem('end')) self.tableTime.setItem(1, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(2, 0, QTableWidgetItem('duration')) self.tableTime.setItem(2, 1, QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QtGui.QTableWidget(max_arg_num, 2) self.tableArgs.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_arg_num): self.tableArgs.setItem(idx, 0, QTableWidgetItem()) self.tableArgs.setItem(idx, 1, QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QtGui.QTableWidget(max_ret_num, 2) self.tableRet.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_ret_num): self.tableRet.setItem(idx, 0, QTableWidgetItem()) self.tableRet.setItem(idx, 1, QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect( self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy) def reset(self): for idx in reversed(range(0, self.listThread.count())): self.listThread.takeItem(idx) def setMsgInfoMessage(self, msg): self.strMessage = msg def changeHideCircularMessage(self, state): if state == QtCore.Qt.Unchecked: self.diagramView.hideCircularChanged(False) elif state == QtCore.Qt.Checked: self.diagramView.hideCircularChanged(True) def setMsgInfoModule(self, module): self.strModule = module def updateSearchStatus(self, curr, number): self.searchCursor.setText("%d/%d" % (curr, number)) def connectSourceViewer(self, viewer): self.srcViewer = viewer def openSourceViewer(self): self.srcViewer.openViewer(self.strModule, self.strMessage) def setMessageInfoTime(self, begin, end, duration): self.tableTime.item(0, 1).setText(begin) self.tableTime.item(1, 1).setText(end) self.tableTime.item(2, 1).setText(duration + ' msec') def setMessageInfoArg(self, listParam, listArg): if listArg: for idx, text in enumerate(listArg): self.tableArgs.item(idx, 1).setText(text) for idx, text in enumerate(listParam): self.tableArgs.item(idx, 0).setText(text) else: for idx in range(0, self.tableArgs.rowCount()): self.tableArgs.item(idx, 1).setText('') self.tableArgs.item(idx, 0).setText('') def setMessageInfoRet(self, listRet): if listRet: for idx, text in enumerate(listRet): self.tableRet.item(idx, 1).setText(text) else: for idx in range(0, self.tableRet.rowCount()): self.tableRet.item(idx, 1).setText('') self.tableRet.item(idx, 0).setText('') def notifyInteractiveStateChanged(self, state): if const.mode_interactive != self.mode: return if const.STATE_INTERACTIVE_CAPTURING == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Stop Capture') if const.STATE_INTERACTIVE_PROCESSING == state: self.buttonCapture.setEnabled(False) if const.STATE_INTERACTIVE_IDLE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') if const.STATE_INTERACTIVE_RESET == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') elif const.STATE_INTERACTIVE_ACTIVE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') def setMessageInfo(self, info): self.msgInfo.setText(info) def setAvailable(self, threads): self.sig.emit(threads) def toggleThreadDisplay(self, item): print(self.listThread.currentRow()) #if item.isSelected(): # print(item.text() + " is selected") #else: # print(item.text() + " is not selected") self.diagramView.showThread(self.listThread.currentRow(), item.isSelected()) def hideAllMsgNamedAsSelected(self): self.diagramView.hideAllMessageSelected() def addThreadList(self, threads): if not self.groupBoxThreadInfo: self.groupBoxThreadInfo = QGroupBox() self.threadInfo = QLabel("Thread Info.") self.groupBoxThreadInfo.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;" ) if not self.threadvbox: self.threadvbox = QVBoxLayout() if not self.listThread: self.listThread = QListWidget() self.listThread.setFixedWidth(200) self.listThread.setSelectionMode( QtGui.QAbstractItemView.MultiSelection) QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay) self.threadvbox.addWidget(self.threadInfo) self.threadvbox.addWidget(self.listThread) self.groupBoxThreadInfo.setLayout(self.threadvbox) self.addWidget(self.groupBoxThreadInfo) self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy) for id in threads: item = QtGui.QListWidgetItem(id) self.listThread.addItem(item) def connectController(self, controller): self.controller = controller self.connect(controller, QtCore.SIGNAL('setAvailable()'), self.setAvailable) def connectDiagramView(self, view): self.diagramView = view def disconnectMsgRcv(self, receiver): print("Implement this method !!! disconnectMsgRcv") def connectMsgRcv(self, receiver): self.msgRcv.append(receiver) def notifyHide(self): for rcv in self.msgRcv: rcv.activateHide(True) def showHiddenLifelines(self): response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems( self.diagramView.getHiddenLifeLines()) if response: self.diagramView.showLifelines(selected_items) def showHiddenMessages(self): response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems( self.diagramView.getHiddenMessages(), self.diagramView.getHiddenLifeLines()) if response: if selected_items[3] in self.diagramView.getHiddenLifeLines(): confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine( selected_items[3]) if confirmation: self.diagramView.showLifelines([selected_items[3]]) self.diagramView.showMessages(selected_items) else: self.diagramView.showMessages(selected_items) def notifyCapture(self): for rcv in self.msgRcv: rcv.activateCapture(True) def moveToPrev(self): for rcv in self.msgRcv: rcv.moveToPrev() def moveToNext(self): for rcv in self.msgRcv: rcv.moveToNext() def searchMsg(self): str = self.editTextSearch.toPlainText() for rcv in self.msgRcv: rcv.searchMessage(str)
def createEditor(self,parent,option,index): editor = QCheckBox(parent) if option: editor.setGeometry(option.rect) return editor
class RangeWidget(QWidget): """Interface for changing Range information. It shows the current range and range policy. This widget was designed for use with the tab dialog. It can be used by itself or it can be used as part of a bigger color tab. Changes to this widget are emitted via a changeSignal as a boolean on policy, range tuple and this widget's tag. """ changeSignal = Signal(bool, float, float, str) def __init__(self, parent, use_max, current_range, max_range, tag): """Creates a ColorMap widget. parent The Qt parent of this widget. use_max Whether the policy is to use max possible or set range. current_range The min and max range on creation. tag A name for this widget, will be emitted on change. """ super(RangeWidget, self).__init__(parent) self.edit_range = (current_range[0], current_range[1]) self.max_range = max_range self.use_max = use_max self.tag = tag layout = QVBoxLayout() self.range_check = QCheckBox("Use maximum range across applicable " + "modules.") layout.addWidget(self.range_check) if self.use_max: self.range_check.setChecked(True) else: self.range_check.setChecked(False) self.range_check.stateChanged.connect(self.checkChanged) layout.addItem(QSpacerItem(3, 3)) hlayout = QHBoxLayout() hlayout.addWidget(QLabel("Set range: ")) self.range_min = QLineEdit(str(current_range[0]), self) self.range_min.editingFinished.connect(self.rangeChanged) hlayout.addWidget(self.range_min) hlayout.addWidget(QLabel(" to ")) self.range_max = QLineEdit(str(current_range[1]), self) self.range_max.editingFinished.connect(self.rangeChanged) hlayout.addWidget(self.range_max) layout.addLayout(hlayout) self.setStates() self.setLayout(layout) def setStates(self): if self.use_max: self.range_min.setDisabled(True) self.range_max.setDisabled(True) else: self.range_min.setDisabled(False) self.range_max.setDisabled(False) @Slot() def checkChanged(self): """Handles check/uncheck of use max.""" self.use_max = self.range_check.isChecked() self.setStates() if self.use_max: self.changeSignal.emit(self.use_max, self.max_range[0], self.max_range[1], self.tag) else: self.changeSignal.emit(self.use_max, self.edit_range[0], self.edit_range[1], self.tag) @Slot() def rangeChanged(self): self.edit_range = (float(self.range_min.text()), float(self.range_max.text())) self.changeSignal.emit(self.use_max, self.edit_range[0], self.edit_range[1], self.tag)
def __init__(self, parent): super(self.__class__, self).__init__(parent) self.parent = parent self.lib = libserial.InitApp(self) if self.parent.receive is not None: self.boolean_config_is_ok = True else: self.boolean_config_is_ok = False self.config_parser = ConfigParser.ConfigParser() self.config_parser.read("config/profiles/profiles.ini") self.settings_parser = ConfigParser.ConfigParser() self.settings_parser.read('config/settings.ini') self.setWindowTitle(SERIAL_CHAT_SETTINGS_TITLE) self.button_box_dialog = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.button_box_dialog.button(QDialogButtonBox.Ok).setText(CONNECT) self.button_box_dialog.button(QDialogButtonBox.Cancel).setText(CANCEL) self.button_box_dialog.accepted.connect(self.accept) self.accepted.connect(self.apply_setting_changes) self.button_box_dialog.rejected.connect(self.reject) self.serial_dropdown = QComboBox() self.lib.init__serial() self.serial_values = self.lib.get_serials() for serials in self.serial_values: self.serial_dropdown.addItem(serials) if self.parent.serial_port is not None: self.serial_dropdown.setCurrentIndex( self.serial_dropdown.findText(self.parent.serial_port.name)) self.profiles_combobox = QComboBox() self.profiles_combobox.addItem("None") if self.parent.choosen_profile == "Custom": self.profiles_combobox.addItem("Custom") for profile in self.config_parser.sections(): self.profiles_combobox.addItem(profile) if self.parent.custom_settings: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('Custom')) elif self.parent.choosen_profile != 'None': self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText(self.parent.choosen_profile)) else: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('None')) self.profiles_combobox.currentIndexChanged.connect( self.change_custom_settings_on_profile) self.custom_settings_checkbox = QCheckBox() self.custom_settings_checkbox.stateChanged.connect( self.custom_settings_enable_disable) self.interval_time_lineedit = QLineEdit(str(self.parent.interval_time)) self.interval_time_lineedit.editingFinished.connect( self.check_if_digit) self.interval_time_lineedit.setDisabled(True) self.serial_speed_combobox = QComboBox() for sp in serial_speeds: self.serial_speed_combobox.addItem(str(sp)) if self.boolean_config_is_ok: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText( str(self.parent.serial_port.baudrate))) else: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText('9600')) self.serial_speed_combobox.setDisabled(True) self.databits_combobox = QComboBox() for db in bytesize_values: self.databits_combobox.addItem(str(db)) if self.boolean_config_is_ok: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText( str(self.parent.serial_port.bytesize))) else: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText('8')) self.databits_combobox.setDisabled(True) self.stopbits_combobox = QComboBox() for sb in stop_values: self.stopbits_combobox.addItem(str(sb)) if self.boolean_config_is_ok: sb = str(self.parent.serial_port.stopbits).replace('.', ',') self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText(str(sb))) else: self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText('1')) self.stopbits_combobox.setDisabled(True) self.parity_combobox = QComboBox() for par in parity_values: self.parity_combobox.addItem(str(par)) if self.boolean_config_is_ok: table = {'O': 'Odd', 'E': 'Even', 'N': 'None'} xxx = [ item for key, item in table.items() if self.parent.serial_port.parity == key ] self.parity_combobox.setCurrentIndex(parity_values.index(xxx[0])) else: self.parity_combobox.setCurrentIndex( self.parity_combobox.findText("None")) self.parity_combobox.setDisabled(True) self.flowcontrol_combobox = QComboBox() for fc in flow_control_values: self.flowcontrol_combobox.addItem(str(fc)) if self.boolean_config_is_ok: if self.parent.serial_port.xonxoff: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("XON/XOFF")) elif self.parent.serial_port.rtscts: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("RTS/CTS")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) self.flowcontrol_combobox.setDisabled(True) self.nickname_lineedit = QLineEdit() if self.settings_parser.has_option('default', 'nickname'): nickname = self.settings_parser.get('default', 'nickname') if type(nickname) == str: nickname = nickname.decode('utf-8') self.nickname_lineedit.setText( self.settings_parser.get('default', 'nickname')) else: if self.parent.nickname is None: self.nickname_lineedit.setText("Guest_" + MD5.new( str(datetime.datetime.now())).digest().encode('hex')[:5]) else: self.nickname_lineedit.setText(self.parent.nickname) self.save_folder_editline = QLineEdit(self.parent.default_save_folder) self.save_folder_editline.editingFinished.connect( self.check_if_folder_exists) if self.settings_parser.has_option('default', 'default_save_folder'): folder = self.settings_parser.get('default', 'default_save_folder') if type(folder) == str: folder = folder.decode('utf-8') self.save_folder_editline.setText(folder) self.check_if_folder_exists() self.dir_browser_button = QPushButton() self.dir_browser_button.setIcon(QIcon(icons_folder + 'folder.png')) self.dir_browser_button.clicked.connect(self.choose_save_dir) self.horizontal_box_hboxlayout = QHBoxLayout() self.horizontal_box_hboxlayout.addWidget(self.save_folder_editline) self.horizontal_box_hboxlayout.addWidget(self.dir_browser_button) self.horizontal_box_container_widget = QWidget() self.horizontal_box_container_widget.setLayout( self.horizontal_box_hboxlayout) self.enable_ACP127 = QCheckBox() self.enable_ACP127.stateChanged.connect( self.enable_functionality_ACP127) if self.parent.acp127: self.enable_ACP127.setChecked(True) self.encryption_password_lineedit = QLineEdit() self.enable_encryption_checkbox = QCheckBox() self.enable_encryption_checkbox.stateChanged.connect( self.enable_functionality_encryption) if self.parent.isEncryptionEnabled: self.enable_encryption_checkbox.setChecked(True) self.encryption_password_lineedit.setEchoMode( QLineEdit.EchoMode.PasswordEchoOnEdit) if self.parent.encryption_key is not None: self.encryption_password_lineedit.setText( self.parent.encryption_key) if self.enable_encryption_checkbox.isChecked(): self.encryption_password_lineedit.setDisabled(False) else: self.encryption_password_lineedit.setDisabled(True) self.grid_form_layout = QFormLayout() self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_TITLE + ":", self.serial_dropdown) self.grid_form_layout.addRow(FORMLAYOUT_PROFILE_TITLE + ":", self.profiles_combobox) self.grid_form_layout.addRow(FORMLAYOUT_CUSTOM_SERIAL_SETTINGS_TITLE, self.custom_settings_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_INTERVAL_TIME_TITLE + ":", self.interval_time_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_SPEED_TITLE + "(baud):", self.serial_speed_combobox) self.grid_form_layout.addRow(FORMLAYOUT_DATA_BITS_TITLE + ":", self.databits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_STOP_BITS_TITLE + ":", self.stopbits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_PARITY_TITLE + ":", self.parity_combobox) self.grid_form_layout.addRow(FORMLAYOUT_FLOWCONTROL_TITLE + ":", self.flowcontrol_combobox) self.grid_form_layout.addRow( FORMLAYOUT_ENABLE_ACP127_TITLE + " ACP-127", self.enable_ACP127) self.grid_form_layout.addRow(FORMLAYOUT_ENABLE_ENCRYPTION_TITLE, self.enable_encryption_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_ENCRYPTION_KEY_TITLE, self.encryption_password_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_NICKNAME_TITLE + ":", self.nickname_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SAVE_FOLDER_FILE_TITLE + ":", self.horizontal_box_container_widget) self.grid_form_layout.addRow("", self.button_box_dialog) self.setLayout(self.grid_form_layout) self.show()
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("Recreate Entries — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.populate() self.updateUi() self.createConnections() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.listWidget = Widgets.List.HtmlListWidget(self.state) self.tooltips.append((self.listWidget, """\ <p><b>Recreatable Entries view</b></p> <p>The list of this index's recreatable entries.</p>""")) self.recreateSubentriesCheckBox = QCheckBox("Recreate &Subentries") self.recreateSubentriesCheckBox.setChecked(True) self.tooltips.append((self.recreateSubentriesCheckBox, """\ <p><b>Recreate Subentries</b></p> <p>If checked, when an entry or subentry is recreated, all of its subentries, and their subentries, and so on (if any), will also be recrected if possible.</p>""")) self.recreateButton = QPushButton(QIcon(":/recreate.svg"), "&Recreate") self.recreateButton.setDefault(True) self.recreateButton.setAutoDefault(True) self.tooltips.append((self.recreateButton, """\ <p><b>Recreate</b></p> <p>Recreate the current entry or subentry (and its subentries and their subentries, and so on, if the <b>Recreate Subentries</b> checkbox is checked), and then close the dialog.</p> <p>Note that it is possible to get rid of the recreated entries by clicking <b>Index→Undo</b> immediately after the dialog closes. (Or, at any later time by simply deleting them.)""")) self.deleteButton = QPushButton(QIcon(":/delete.svg"), "&Delete...") self.tooltips.append((self.deleteButton, """\ <p><b>Delete</b></p> <p>Permanently delete the current recreatable entry or subentry from this index's list of recreatable entries.</p>""")) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Recreate Entries dialog")) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Close</b></p> <p>Close the dialog.</p>""")) def layoutWidgets(self): buttonBox = QDialogButtonBox() buttonBox.addButton(self.recreateButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.deleteButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.closeButton, QDialogButtonBox.AcceptRole) buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) layout = QVBoxLayout() layout.addWidget(self.listWidget) layout.addWidget(self.recreateSubentriesCheckBox) layout.addWidget(buttonBox) self.setLayout(layout) def createConnections(self): self.recreateButton.clicked.connect(self.recreate) self.deleteButton.clicked.connect(self.delete) self.closeButton.clicked.connect(self.reject) self.helpButton.clicked.connect(self.help) def help(self): self.state.help("xix_ref_dlg_recreate.html") def updateUi(self): enable = self.listWidget.currentRow() > -1 self.recreateButton.setEnabled(enable) self.deleteButton.setEnabled(enable) def populate(self): self.listWidget.clear() for entry in self.state.model.deletedEntries(): pages = "" if entry.pages: pages = ", {}".format(entry.pages) top = MAIN_INDICATOR if entry.peid == ROOT else SUB_INDICATOR item = QListWidgetItem("{} {}{}".format( top, Lib.elidePatchHtml(entry.term, self.state), Lib.elidePatchHtml(pages, self.state))) item.setData(Qt.UserRole, entry.eid) self.listWidget.addItem(item) if self.listWidget.count(): self.listWidget.setCurrentRow(0) def recreate(self): # No need to restore focus widget item = self.listWidget.currentItem() if item: eid = item.data(Qt.UserRole) subentries = self.recreateSubentriesCheckBox.isChecked() with Lib.DisableUI(self): self.state.model.recreateEntry(eid, subentries) say("Recreated", SAY_TIMEOUT) self.accept() def delete(self): widget = QApplication.focusWidget() item = self.listWidget.currentItem() if item: eid = item.data(Qt.UserRole) if self.state.model.hasDeletedEntry(eid): with Lib.Qt.DisableUI(self, forModalDialog=True): reply = QMessageBox.question( self, "Delete Revivable Entry — {}".format( QApplication.applicationName()), "<p>Permanently delete revivable entry<br>“{}”?". format(item.text()), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: with Lib.DisableUI(self): self.state.model.deleteDeletedEntry(eid) self.populate() self.updateUi() Lib.restoreFocus(widget)
class UI(gobject.GObject): __gsignals__ = { 'command': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING, )) } def __init__(self, args, continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400, 200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttons self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) #add the actions for quiting quit_action = QAction(self.window) quit_action.setShortcut('Ctrl+Q') quit_action.triggered.connect(self.accel_quit) self.window.addAction(quit_action) def accel_quit(self): #emit the quit self.emit("command", "quit") def ccheckbox_clicked(self): checked = self.ccheckbox.isChecked() if checked: #disable lsbutton self.lsbutton.setEnabled(False) self.lsbutton_stopped() self.emit('command', "continuous_listen") else: self.lsbutton.setEnabled(True) self.emit('command', "continuous_stop") def lsbutton_stopped(self): self.lsbutton.setText("Listen") def lsbutton_clicked(self): val = self.lsbutton.text() if val == "Listen": self.emit("command", "listen") self.lsbutton.setText("Stop") #clear the label self.label.setText("") else: self.lsbutton_stopped() self.emit("command", "stop") def run(self): self.window.show() if self.continuous: self.ccheckbox.setCheckState(Qt.Checked) self.ccheckbox_clicked() self.app.exec_() self.emit("command", "quit") def finished(self, text): print text #if the continuous isn't pressed if not self.ccheckbox.isChecked(): self.lsbutton_stopped() self.label.setText(text) def set_icon(self, icon): self.window.setWindowIcon(QIcon(icon))
class Panel(QWidget): def __init__(self, state, config, parent): super().__init__(parent) self.state = state self.config = config self.form = parent self.createWidgets() self.layoutWidgets() self.createConnections() def createWidgets(self): settings = QSettings() self.sortRulesGroupBox = QGroupBox("Calculate &Sort As Rules") defaultSortAsRules = settings.value(Gconf.Key.SortAsRules, Gopt.Default.SortAsRules) self.thisSortAsRules = self.config.get(Gopt.Key.SortAsRules, defaultSortAsRules) self.defaultSortAsRulesBox = QComboBox() self.form.tooltips.append((self.defaultSortAsRulesBox, """\ <p><b>Calculate Sort As Rules, Default</b></p> <p>The default setting for the <b>Calculate Sort As Rules, For This Index</b> combobox for new indexes.</p>""")) self.thisSortAsRulesBox = QComboBox() self.form.tooltips.append((self.thisSortAsRulesBox, """\ <p><b>Calculate Sort As Rules, For This Index</b></p> <p>The rules to use for calculating each entry's sort as text for this index.</p> <p>If the rules are changed, when the dialog is closed, the new rules will be applied to every entry in the index.</p>""")) self.populateSortAsRulesBox(self.defaultSortAsRulesBox, defaultSortAsRules) self.populateSortAsRulesBox(self.thisSortAsRulesBox, self.thisSortAsRules) self.pageRangeRulesBox = QGroupBox("&Page Range Rules") defaultPageRangeRules = settings.value(Gconf.Key.PageRangeRules, Gopt.Default.PageRangeRules) self.thisPageRangeRules = self.config.get(Gopt.Key.PageRangeRules, defaultPageRangeRules) self.defaultPageRangeRulesBox = QComboBox() self.form.tooltips.append((self.defaultPageRangeRulesBox, """\ <p><b>Page Range Rules, Default</b></p> <p>The default setting for the <b>Page Range Rules, For This Index</b> combobox for new indexes.</p>""")) self.thisPageRangeRulesBox = QComboBox() self.form.tooltips.append((self.thisPageRangeRulesBox, """\ <p><b>Page Range Rules, For This Index</b></p> <p>The rules to use for handling page ranges, e.g., whether in full such as 120–124, or somehow compressed, e.g., 120–4, for this index.</p> <p>If the rules are changed, when the dialog is closed, the new rules will be applied to every entry in the index.</p>""")) self.populatePageRangeRulesBox(self.defaultPageRangeRulesBox, defaultPageRangeRules) self.populatePageRangeRulesBox(self.thisPageRangeRulesBox, self.thisPageRangeRules) self.padDigitsGroupBox = QGroupBox("Pad &Digits") defaultPadDigits = int( settings.value(Gconf.Key.PadDigits, Gopt.Default.PadDigits)) self.thisPadDigits = int( self.config.get(Gopt.Key.PadDigits, defaultPadDigits)) self.thisPadDigitsLabel = QLabel("For This Index") self.thisPadDigitsSpinBox = QSpinBox() self.thisPadDigitsSpinBox.setAlignment(Qt.AlignRight) self.thisPadDigitsSpinBox.setRange(0, 12) self.thisPadDigitsSpinBox.setValue(self.thisPadDigits) self.form.tooltips.append((self.thisPadDigitsSpinBox, """\ <p><b>Pad Digits, For This Index</b></p> <p>Sort as texts are compared textually, so if a term contains a number (or text which is converted to a number), the number must be padded by leading zeros to ensure correct ordering. This is the number of digits to pad for, for this index. For example, if set to 4, the numbers 1, 23, and 400 would be set to 0001, 0023, and 0400, in the sort as text.</p>""")) self.defaultPadDigitsLabel = QLabel("Default") self.defaultPadDigitsSpinBox = QSpinBox() self.defaultPadDigitsSpinBox.setAlignment(Qt.AlignRight) self.defaultPadDigitsSpinBox.setRange(0, 12) self.defaultPadDigitsSpinBox.setValue(defaultPadDigits) self.form.tooltips.append((self.defaultPadDigitsSpinBox, """\ <p><b>Pad Digits, Default</b></p> <p>The default setting for the <b>Pad Digits, For This Index</b> spinbox for new indexes.</p>""")) self.ignoreSubFirstsGroupBox = QGroupBox( "&Ignore Subentry Function Words") defaultIgnoreSubFirsts = bool( int( settings.value(Gconf.Key.IgnoreSubFirsts, Gopt.Default.IgnoreSubFirsts))) thisIgnoreSubFirsts = bool( int( self.config.get(Gopt.Key.IgnoreSubFirsts, defaultIgnoreSubFirsts))) self.thisIgnoreSubFirstsCheckBox = QCheckBox("For This Index") self.thisIgnoreSubFirstsCheckBox.setChecked(thisIgnoreSubFirsts) self.form.tooltips.append((self.thisIgnoreSubFirstsCheckBox, """\ <p><b>Ignore Subentry Function Words, For This Index</b></p> <p>This setting applies to this index.</p> <p>If checked, words listed in the <b>Index→Ignore Subentry Function Words</b> list are ignored for sorting purposes when the first word of a subentry, i.e., ignored when the first word of an entry's sort as text.</p> <p>This should normally be checked for Chicago Manual of Style Sort As Rules, and unchecked for NISO Rules.</p>""")) self.defaultIgnoreSubFirstsCheckBox = QCheckBox("Default") self.defaultIgnoreSubFirstsCheckBox.setChecked(defaultIgnoreSubFirsts) self.form.tooltips.append((self.defaultIgnoreSubFirstsCheckBox, """\ <p><b>Ignore Subentry Function Words, Default</b></p> <p>The default setting for the <b>Ignore Subentry Function Words, For This Index</b> checkbox for new indexes</p>""")) self.suggestSpelledGroupBox = QGroupBox( "&Suggest Spelled Out Numbers when Appropriate") defaultSuggestSpelled = bool( int( settings.value(Gconf.Key.SuggestSpelled, Gopt.Default.SuggestSpelled))) thisSuggestSpelled = bool( int(self.config.get(Gopt.Key.SuggestSpelled, defaultSuggestSpelled))) self.thisSuggestSpelledCheckBox = QCheckBox("For This Index") self.thisSuggestSpelledCheckBox.setChecked(thisSuggestSpelled) self.form.tooltips.append((self.thisSuggestSpelledCheckBox, """\ <p><b>Suggest Spelled Out Numbers when Appropriate, For This Index</b></p> <p>When checked (and providing the Sort As rules in force are not NISO rules), when adding or editing a term when the <b>Automatically Calculate Sort As</b> checkbox is checked, and when the term contains a number, the choice of sort as texts will include the number spelled out.</p>""")) self.defaultSuggestSpelledCheckBox = QCheckBox("Default") self.defaultSuggestSpelledCheckBox.setChecked(defaultSuggestSpelled) self.form.tooltips.append((self.defaultSuggestSpelledCheckBox, """\ <p><b>Suggest Spelled Out Numbers when Appropriate, Default</b></p> <p>The default setting for the <b>Suggest Spelled Out Numbers when Appropriate, For This Index</b> checkbox for new indexes.</p>""")) def layoutWidgets(self): layout = QVBoxLayout() form = QFormLayout() form.addRow("For This Index", self.thisSortAsRulesBox) form.addRow("Default", self.defaultSortAsRulesBox) self.sortRulesGroupBox.setLayout(form) layout.addWidget(self.sortRulesGroupBox) form = QFormLayout() form.addRow("For This Index", self.thisPageRangeRulesBox) form.addRow("Default", self.defaultPageRangeRulesBox) self.pageRangeRulesBox.setLayout(form) layout.addWidget(self.pageRangeRulesBox) hbox = QHBoxLayout() hbox.addWidget(self.thisPadDigitsLabel) hbox.addWidget(self.thisPadDigitsSpinBox) hbox.addStretch(1) hbox.addWidget(self.defaultPadDigitsLabel) hbox.addWidget(self.defaultPadDigitsSpinBox) hbox.addStretch(3) self.padDigitsGroupBox.setLayout(hbox) layout.addWidget(self.padDigitsGroupBox) hbox = QHBoxLayout() hbox.addWidget(self.thisIgnoreSubFirstsCheckBox) hbox.addWidget(self.defaultIgnoreSubFirstsCheckBox) hbox.addStretch() self.ignoreSubFirstsGroupBox.setLayout(hbox) layout.addWidget(self.ignoreSubFirstsGroupBox) hbox = QHBoxLayout() hbox.addWidget(self.thisSuggestSpelledCheckBox) hbox.addWidget(self.defaultSuggestSpelledCheckBox) hbox.addStretch() self.suggestSpelledGroupBox.setLayout(hbox) layout.addWidget(self.suggestSpelledGroupBox) layout.addStretch() self.setLayout(layout) def createConnections(self): self.defaultSortAsRulesBox.currentIndexChanged.connect( self.setDefaultSortAsRules) self.defaultPageRangeRulesBox.currentIndexChanged.connect( self.setDefaultPageRangeRules) self.defaultPadDigitsSpinBox.valueChanged.connect( self.setDefaultPadDigits) self.defaultIgnoreSubFirstsCheckBox.toggled.connect( self.setDefaultIgnoreSubFirsts) self.defaultSuggestSpelledCheckBox.toggled.connect( self.setDefaultSuggestSpelled) def populateSortAsRulesBox(self, combobox, rules): index = -1 for i, name in enumerate(SortAs.RulesForName): displayName = SortAs.RulesForName[name].name combobox.addItem(displayName, name) if name == rules: index = i combobox.setCurrentIndex(index) def setDefaultSortAsRules(self, index): index = self.defaultSortAsRulesBox.currentIndex() name = self.defaultSortAsRulesBox.itemData(index) settings = QSettings() settings.setValue(Gopt.Key.SortAsRules, name) def populatePageRangeRulesBox(self, combobox, rules): index = -1 for i, name in enumerate(Pages.RulesForName): displayName = Pages.RulesForName[name].name combobox.addItem(displayName, name) if name == rules: index = i combobox.setCurrentIndex(index) def setDefaultPageRangeRules(self, index): index = self.defaultPageRangeRulesBox.currentIndex() name = self.defaultPageRangeRulesBox.itemData(index) settings = QSettings() settings.setValue(Gopt.Key.PageRangeRules, name) def setDefaultPadDigits(self): value = self.defaultPadDigitsSpinBox.value() settings = QSettings() settings.setValue(Gopt.Key.PadDigits, value) def setDefaultIgnoreSubFirsts(self): value = int(self.defaultIgnoreSubFirstsCheckBox.isChecked()) settings = QSettings() settings.setValue(Gopt.Key.IgnoreSubFirsts, value) def setDefaultSuggestSpelled(self): value = int(self.defaultSuggestSpelledCheckBox.isChecked()) settings = QSettings() settings.setValue(Gopt.Key.SuggestSpelled, value)
def createWidgets(self): settings = QSettings() self.sortRulesGroupBox = QGroupBox("Calculate &Sort As Rules") defaultSortAsRules = settings.value(Gconf.Key.SortAsRules, Gopt.Default.SortAsRules) self.thisSortAsRules = self.config.get(Gopt.Key.SortAsRules, defaultSortAsRules) self.defaultSortAsRulesBox = QComboBox() self.form.tooltips.append((self.defaultSortAsRulesBox, """\ <p><b>Calculate Sort As Rules, Default</b></p> <p>The default setting for the <b>Calculate Sort As Rules, For This Index</b> combobox for new indexes.</p>""")) self.thisSortAsRulesBox = QComboBox() self.form.tooltips.append((self.thisSortAsRulesBox, """\ <p><b>Calculate Sort As Rules, For This Index</b></p> <p>The rules to use for calculating each entry's sort as text for this index.</p> <p>If the rules are changed, when the dialog is closed, the new rules will be applied to every entry in the index.</p>""")) self.populateSortAsRulesBox(self.defaultSortAsRulesBox, defaultSortAsRules) self.populateSortAsRulesBox(self.thisSortAsRulesBox, self.thisSortAsRules) self.pageRangeRulesBox = QGroupBox("&Page Range Rules") defaultPageRangeRules = settings.value(Gconf.Key.PageRangeRules, Gopt.Default.PageRangeRules) self.thisPageRangeRules = self.config.get(Gopt.Key.PageRangeRules, defaultPageRangeRules) self.defaultPageRangeRulesBox = QComboBox() self.form.tooltips.append((self.defaultPageRangeRulesBox, """\ <p><b>Page Range Rules, Default</b></p> <p>The default setting for the <b>Page Range Rules, For This Index</b> combobox for new indexes.</p>""")) self.thisPageRangeRulesBox = QComboBox() self.form.tooltips.append((self.thisPageRangeRulesBox, """\ <p><b>Page Range Rules, For This Index</b></p> <p>The rules to use for handling page ranges, e.g., whether in full such as 120–124, or somehow compressed, e.g., 120–4, for this index.</p> <p>If the rules are changed, when the dialog is closed, the new rules will be applied to every entry in the index.</p>""")) self.populatePageRangeRulesBox(self.defaultPageRangeRulesBox, defaultPageRangeRules) self.populatePageRangeRulesBox(self.thisPageRangeRulesBox, self.thisPageRangeRules) self.padDigitsGroupBox = QGroupBox("Pad &Digits") defaultPadDigits = int( settings.value(Gconf.Key.PadDigits, Gopt.Default.PadDigits)) self.thisPadDigits = int( self.config.get(Gopt.Key.PadDigits, defaultPadDigits)) self.thisPadDigitsLabel = QLabel("For This Index") self.thisPadDigitsSpinBox = QSpinBox() self.thisPadDigitsSpinBox.setAlignment(Qt.AlignRight) self.thisPadDigitsSpinBox.setRange(0, 12) self.thisPadDigitsSpinBox.setValue(self.thisPadDigits) self.form.tooltips.append((self.thisPadDigitsSpinBox, """\ <p><b>Pad Digits, For This Index</b></p> <p>Sort as texts are compared textually, so if a term contains a number (or text which is converted to a number), the number must be padded by leading zeros to ensure correct ordering. This is the number of digits to pad for, for this index. For example, if set to 4, the numbers 1, 23, and 400 would be set to 0001, 0023, and 0400, in the sort as text.</p>""")) self.defaultPadDigitsLabel = QLabel("Default") self.defaultPadDigitsSpinBox = QSpinBox() self.defaultPadDigitsSpinBox.setAlignment(Qt.AlignRight) self.defaultPadDigitsSpinBox.setRange(0, 12) self.defaultPadDigitsSpinBox.setValue(defaultPadDigits) self.form.tooltips.append((self.defaultPadDigitsSpinBox, """\ <p><b>Pad Digits, Default</b></p> <p>The default setting for the <b>Pad Digits, For This Index</b> spinbox for new indexes.</p>""")) self.ignoreSubFirstsGroupBox = QGroupBox( "&Ignore Subentry Function Words") defaultIgnoreSubFirsts = bool( int( settings.value(Gconf.Key.IgnoreSubFirsts, Gopt.Default.IgnoreSubFirsts))) thisIgnoreSubFirsts = bool( int( self.config.get(Gopt.Key.IgnoreSubFirsts, defaultIgnoreSubFirsts))) self.thisIgnoreSubFirstsCheckBox = QCheckBox("For This Index") self.thisIgnoreSubFirstsCheckBox.setChecked(thisIgnoreSubFirsts) self.form.tooltips.append((self.thisIgnoreSubFirstsCheckBox, """\ <p><b>Ignore Subentry Function Words, For This Index</b></p> <p>This setting applies to this index.</p> <p>If checked, words listed in the <b>Index→Ignore Subentry Function Words</b> list are ignored for sorting purposes when the first word of a subentry, i.e., ignored when the first word of an entry's sort as text.</p> <p>This should normally be checked for Chicago Manual of Style Sort As Rules, and unchecked for NISO Rules.</p>""")) self.defaultIgnoreSubFirstsCheckBox = QCheckBox("Default") self.defaultIgnoreSubFirstsCheckBox.setChecked(defaultIgnoreSubFirsts) self.form.tooltips.append((self.defaultIgnoreSubFirstsCheckBox, """\ <p><b>Ignore Subentry Function Words, Default</b></p> <p>The default setting for the <b>Ignore Subentry Function Words, For This Index</b> checkbox for new indexes</p>""")) self.suggestSpelledGroupBox = QGroupBox( "&Suggest Spelled Out Numbers when Appropriate") defaultSuggestSpelled = bool( int( settings.value(Gconf.Key.SuggestSpelled, Gopt.Default.SuggestSpelled))) thisSuggestSpelled = bool( int(self.config.get(Gopt.Key.SuggestSpelled, defaultSuggestSpelled))) self.thisSuggestSpelledCheckBox = QCheckBox("For This Index") self.thisSuggestSpelledCheckBox.setChecked(thisSuggestSpelled) self.form.tooltips.append((self.thisSuggestSpelledCheckBox, """\ <p><b>Suggest Spelled Out Numbers when Appropriate, For This Index</b></p> <p>When checked (and providing the Sort As rules in force are not NISO rules), when adding or editing a term when the <b>Automatically Calculate Sort As</b> checkbox is checked, and when the term contains a number, the choice of sort as texts will include the number spelled out.</p>""")) self.defaultSuggestSpelledCheckBox = QCheckBox("Default") self.defaultSuggestSpelledCheckBox.setChecked(defaultSuggestSpelled) self.form.tooltips.append((self.defaultSuggestSpelledCheckBox, """\ <p><b>Suggest Spelled Out Numbers when Appropriate, Default</b></p> <p>The default setting for the <b>Suggest Spelled Out Numbers when Appropriate, For This Index</b> checkbox for new indexes.</p>"""))
def __init__(self): QWidget.__init__(self) self.setGeometry(QRect(100, 100, 400, 200)) self.layout = QtGui.QGridLayout(self) #lblAssetType self.lblAssetType = QLabel("Asset Type") self.layout.addWidget(self.lblAssetType, 0, 0) #cmdAssetType self.cmdAssetType = QComboBox(self) self.cmdAssetType.addItems(DaoAsset().getAssetTypes()) self.layout.addWidget(self.cmdAssetType, 0, 1) #lblAssetName self.lblAssetName = QLabel("Asset Name") self.layout.addWidget(self.lblAssetName, 1, 0) #cmdAssetName self.cmdAssetName = QComboBox(self) self.layout.addWidget(self.cmdAssetName, 1, 1) #lblCustody self.lblCustody = QLabel("Custody") self.layout.addWidget(self.lblCustody, 2, 0) #cmbCustody self.cmbCustody = QComboBox(self) custodyList = DaoCustody().getCustodyList() for (row) in custodyList: self.cmbCustody.addItem(row[1], row[0]) self.layout.addWidget(self.cmbCustody, 2, 1) #lblBuySell self.lblBuySell = QLabel("Buy Sell") self.layout.addWidget(self.lblBuySell, 3, 0) #cmdBuySell self.cmdBuySell = QComboBox(self) self.cmdBuySell.addItem("BUY") self.cmdBuySell.addItem("SELL") self.layout.addWidget(self.cmdBuySell, 3, 1) #lblByAmount self.lblByAmount = QLabel("By Amount") self.layout.addWidget(self.lblByAmount, 4, 0) #chkByAmount self.chkByAmount = QCheckBox(self) self.layout.addWidget(self.chkByAmount, 4, 1) #lblGrossAmount self.lblGrossAmount = QLabel("Gross Amount") self.layout.addWidget(self.lblGrossAmount, 5, 0) #txtGrossAmount self.txtGrossAmount = QLineEdit(self) self.txtGrossAmount.setValidator(QDoubleValidator( 0, 99999999, 6, self)) self.layout.addWidget(self.txtGrossAmount, 5, 1) #lblAcquisitionDate self.lblAcquisitionDate = QLabel("Acquisition Date") self.layout.addWidget(self.lblAcquisitionDate, 6, 0) #cmdAcquisitionDate self.dateAcquisitionDate = QDateEdit(self) self.dateAcquisitionDate.setDisplayFormat("dd-MM-yyyy") self.dateAcquisitionDate.setDate(datetime.datetime.now()) self.layout.addWidget(self.dateAcquisitionDate, 6, 1) #lblQuantity self.lblQuantity = QLabel("Quantity") self.layout.addWidget(self.lblQuantity, 7, 0) #txtQuantity self.txtQuantity = QLineEdit(self) self.txtQuantity.setValidator(QIntValidator(0, 1000000000, self)) self.layout.addWidget(self.txtQuantity, 7, 1) #lblPrice self.lblPrice = QLabel("Price") self.layout.addWidget(self.lblPrice, 8, 0) #txtPrice self.txtPrice = QLineEdit(self) self.txtPrice.setValidator(QDoubleValidator(0, 99999999, 6, self)) self.layout.addWidget(self.txtPrice, 8, 1) #lblRate self.lblRate = QLabel("Rate") self.layout.addWidget(self.lblRate, 9, 0) #txtRate self.txtRate = QLineEdit(self) self.txtRate.setValidator(QDoubleValidator(0, 99999999, 4, self)) self.txtRate.setEnabled(0) self.layout.addWidget(self.txtRate, 9, 1) #lblNetAmount self.lblNetAmount = QLabel("Net Amount") self.layout.addWidget(self.lblNetAmount, 10, 0) #txtNetAmount self.txtNetAmount = QLineEdit(self) self.txtNetAmount.setEnabled(0) self.txtNetAmount.setValidator(QDoubleValidator(0, 99999999, 6, self)) self.layout.addWidget(self.txtNetAmount, 10, 1) #lblCommissionPercentage self.lblCommissionPercentage = QLabel("Commission Percentage") self.layout.addWidget(self.lblCommissionPercentage, 11, 0) #txtCommissionPercentage self.txtCommissionPercentage = QLineEdit(self) self.txtCommissionPercentage.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionPercentage, 11, 1) #lblCommissionAmount self.lblCommissionAmount = QLabel("Commission Amount") self.layout.addWidget(self.lblCommissionAmount, 12, 0) #txtCommissionAmmount self.txtCommissionAmount = QLineEdit(self) self.txtCommissionAmount.setEnabled(0) self.txtCommissionAmount.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionAmount, 12, 1) #lblCommissionAmount self.lblCommissionVATAmount = QLabel("Commission VAT Amount") self.layout.addWidget(self.lblCommissionVATAmount, 13, 0) #txtCommissionAmmount self.txtCommissionVATAmount = QLineEdit(self) self.txtCommissionVATAmount.setEnabled(0) self.txtCommissionVATAmount.setValidator( QDoubleValidator(0, 9999999, 6, self)) self.layout.addWidget(self.txtCommissionVATAmount, 13, 1) #lblTenor self.lblTenor = QLabel("Tenor") self.layout.addWidget(self.lblTenor, 14, 0) #txtTenor self.txtTenor = QLineEdit(self) self.txtTenor.setEnabled(0) self.txtTenor.setValidator(QDoubleValidator(0, 9999999, 0, self)) self.layout.addWidget(self.txtTenor, 14, 1) #btnAdd self.btnAdd = QPushButton("Add", self) self.layout.addWidget(self.btnAdd) #btnClear self.btnClear = QPushButton("Clear", self) self.layout.addWidget(self.btnClear) #clearEditor self.clearEditor() self.initListener()
class PushupForm(QDialog): ''' classdocs ''' pushupCreated = Signal(Pushup_Model) def __init__(self, athlete): ''' Constructor ''' QDialog.__init__(self) self.setWindowTitle("Pushup form") self.athlete = athlete self.pushupForm = QFormLayout() self.createGUI() def createGUI(self): self.series = QSpinBox() self.series.setMinimum(1) self.repetitions = QSpinBox() self.repetitions.setMaximum(512) self.avgHeartRateToggle = QCheckBox() self.avgHeartRateToggle.toggled.connect(self._toggleHeartRateSpinBox) self.avgHeartRate = QSpinBox() self.avgHeartRate.setMinimum(30) self.avgHeartRate.setMaximum(250) self.avgHeartRate.setValue(120) self.avgHeartRate.setDisabled(True) self.dateSelector_widget = QCalendarWidget() self.dateSelector_widget.setMaximumDate(QDate.currentDate()) self.addButton = QPushButton("Add pushup") self.addButton.setMaximumWidth(90) self.addButton.clicked.connect(self._createPushup) self.cancelButton = QPushButton("Cancel") self.cancelButton.setMaximumWidth(90) self.cancelButton.clicked.connect(self.reject) self.pushupForm.addRow("Series", self.series) self.pushupForm.addRow("Repetitions", self.repetitions) self.pushupForm.addRow("Store average heart rate ? ", self.avgHeartRateToggle) self.pushupForm.addRow("Average Heart Rate", self.avgHeartRate) self.pushupForm.addRow("Exercise Date", self.dateSelector_widget) btnsLayout = QVBoxLayout() btnsLayout.addWidget(self.addButton) btnsLayout.addWidget(self.cancelButton) btnsLayout.setAlignment(Qt.AlignRight) layoutWrapper = QVBoxLayout() layoutWrapper.addLayout(self.pushupForm) layoutWrapper.addLayout(btnsLayout) self.setLayout(layoutWrapper) def _createPushup(self): exerciseDate = self.dateSelector_widget.selectedDate() exerciseDate = self.qDate_to_date(exerciseDate) if self.avgHeartRateToggle.isChecked(): heartRate = self.avgHeartRate.value() else: heartRate = None pushup = Pushup_Model(self.athlete._name, exerciseDate, heartRate, self.series.value(), self.repetitions.value()) self.pushupCreated.emit(pushup) self.accept() def _toggleHeartRateSpinBox(self): if self.avgHeartRateToggle.isChecked(): self.avgHeartRate.setDisabled(False) else: self.avgHeartRate.setDisabled(True) def qDate_to_date(self, qDate): return date(qDate.year(), qDate.month(), qDate.day())
class DataBrowser(QWidget, Ui_DataBrowser): """ @since: 2011-08-24 """ __author__ = "Moritz Wade" __contact__ = "*****@*****.**" __copyright__ = "Zuse Institute Berlin 2011" def __init__(self, parent, id, dataSet): super(DataBrowser, self).__init__(parent) self.setupUi(self) self._simWorkbench = None self.dataService = None self.id = id self.data = dataSet self.optionsService = OptionsService() # create the custom selectable table header self.selectableHeader = SelectableTableHeader(Qt.Horizontal, self.tableView) self.selectableHeader.setNonSelectableIndexes([0]) self.selectableHeader.sectionSelectionChanged.connect( self.on_columnSelectionChanged) self.tableView.setHorizontalHeader(self.selectableHeader) # create the data model self.dataModel = DataBrowserModel(self, self.id, self.data) self.tableView.setModel(self.dataModel) self._setUpSelectionCheckBox() self._updateInfoPane() if not self.optionsService.getDebug(): self.groupBoxPerturbation.setVisible(False) def getId(self): return self.id def setSimulationWorkbench(self, simWorkbench): self._simWorkbench = simWorkbench def getSelectionCheckBox(self): return self._selectionCheckBox def isSelected(self): checkState = self._selectionCheckBox.checkState() return True if checkState == Qt.Checked else False def _setUpSelectionCheckBox(self): self._selectionCheckBox = QCheckBox() self._selectionCheckBox.setChecked(True) infoText = "Select or deselect this data (e.g. to be included in plots and computations)." self._selectionCheckBox.setStatusTip(infoText) self._selectionCheckBox.setToolTip(infoText) self._selectionCheckBox.stateChanged.connect(self._selectionChanged) def _updateInfoPane(self): """ Updates the info pane with basic info about the loaded data and the data file (if any). """ self.lineEditInfoSpecies.setText(str(self.data.getNumOfRealData())) self.lineEditInfoDataType.setText(self.data.type) # self.lineEditInfoFormat.setText(self.data.format) filepath = self.data.filename if filepath and os.path.exists(filepath): self.lineEditInfoPath.setText(filepath) filesize = os.path.getsize(filepath) filesize = filesize / 1024 # displaying kB self.lineEditInfoFilesize.setText("%s kB" % filesize) timeLastModifiedEpoch = os.path.getmtime(filepath) timeLastModified = time.strftime( "%a, %d %b %Y %H:%M:%S", time.localtime(timeLastModifiedEpoch)) self.lineEditInfoLastModified.setText(str(timeLastModified)) else: noFileText = "No File" self.lineEditInfoPath.setText(noFileText) self.lineEditInfoFilesize.setText(noFileText) self.lineEditInfoLastModified.setText(noFileText) def remove(self): """ Cleans up stuff then destroys self. It's not sure whether this is really needed but it might serve to close some memory holes (e.g. dangling references somewhere). """ del self.dataModel del self @Slot() def on_actionPlot_triggered(self): dataDict = {self.data.getId(): self.data} self._simWorkbench.plotExpData(dataDict) @Slot() def on_buttonPerturb_clicked(self): """ Perturbs the data by the % given in self.spinBoxPerturb. """ percentage = self.spinBoxPerturb.value() factor = percentage / 100.0 for entity, entityData in self.data.getData().items(): if not entityData.isSelected(): continue id = entity.getId() if type(entity) == EntityData else str(entity) logging.debug("Perturbing data of EntityData: %s" % id) for i in xrange(len(entityData.datapoints)): value = entityData.datapoints[i] if not value: # for None values continue fraction = value * factor # fraction of value that will be added or substracted #newValue = value + random.uniform(-1 * fraction, fraction) newValue = value + random.uniform(-1, 1) * fraction # newValue = value - fraction if random.random() < 0.5 else value + fraction entityData.setDatapoint(i, newValue) @Slot("") def on_buttonSaveAs_clicked(self): logging.debug("Saving data. Displaying file chooser...") file_choices = "Tab-Delimited Text File *.txt (*.txt)" path = unicode( QFileDialog.getSaveFileName(self, 'Save file', '', file_choices)[0]) if not path.endswith(".txt"): path += ".txt" if path: if not self.dataService: self.dataService = DataService() id = self.data.getId() self.dataService.save_data_as_csv(id, path) logging.info("Saved data to %s" % path) @Slot() def on_buttonTimeshift_clicked(self): """ Timeshift data within this DataBrowser (i.e. DataSet). Not only shift the global timepoints but also the timepoint lists within the individiual EntityData objects. """ try: shiftValue = float(self.lineEditTimeshift.text()) self.dataModel.doTimeshift(shiftValue) except Exception, e: logging.error( "DataBrowser.on_buttonTimeshift_clicked(): Error while timeshifting the data: %s" % e)
def __init__(self, *args, **kwargs): self.minimum = 1 self.maximum = 100 self.lineEditMaximum = 10000 QMainWindow.__init__(self, *args, **kwargs) self.installEventFilter(self) #self.setWindowFlags( QtCore.Qt.Drawer ) self.setWindowTitle(Window_global.title) widgetMain = QWidget() layoutVertical = QVBoxLayout(widgetMain) self.setCentralWidget(widgetMain) layoutSlider = QHBoxLayout() lineEdit = QLineEdit() lineEdit.setFixedWidth(100) lineEdit.setText(str(1)) validator = QIntValidator(self.minimum, self.lineEditMaximum, self) lineEdit.setValidator(validator) slider = QSlider() slider.setOrientation(QtCore.Qt.Horizontal) slider.setMinimum(self.minimum) slider.setMaximum(self.maximum) layoutSlider.addWidget(lineEdit) layoutSlider.addWidget(slider) layoutAngle = QVBoxLayout() checkBox = QCheckBox('Connect Angle By Tangent') layoutVector = QHBoxLayout() leVx = QLineEdit() leVx.setText(str(1.000)) leVx.setEnabled(False) leVx.setValidator(QDoubleValidator(-100, 100, 5, self)) leVy = QLineEdit() leVy.setText(str(0.000)) leVy.setEnabled(False) leVy.setValidator(QDoubleValidator(-100, 100, 5, self)) leVz = QLineEdit() leVz.setText(str(0.000)) leVz.setEnabled(False) leVz.setValidator(QDoubleValidator(-100, 100, 5, self)) layoutAngle.addWidget(checkBox) layoutAngle.addLayout(layoutVector) layoutVector.addWidget(leVx) layoutVector.addWidget(leVy) layoutVector.addWidget(leVz) button = QPushButton('Create') layoutVertical.addLayout(layoutSlider) layoutVertical.addLayout(layoutAngle) layoutVertical.addWidget(button) QtCore.QObject.connect(slider, QtCore.SIGNAL('valueChanged(int)'), self.sliderValueChanged) QtCore.QObject.connect(lineEdit, QtCore.SIGNAL('textEdited(QString)'), self.lineEditValueChanged) QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'), Functions.createPointOnCurve) QtCore.QObject.connect(checkBox, QtCore.SIGNAL('clicked()'), Functions.setAngleEnabled) self.slider = slider self.lineEdit = lineEdit Window_global.slider = slider Window_global.button = button Window_global.checkBox = checkBox Window_global.leVx = leVx Window_global.leVy = leVy Window_global.leVz = leVz
def __init__(self, mode, parentQWidget=None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200, 30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100, 30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;" ) vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QtGui.QTableWidget(3, 2) self.tableTime.setHorizontalHeaderLabels(['-', 'time']) self.tableTime.setColumnWidth(0, 80) self.tableTime.setColumnWidth(1, 150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0, 0, QTableWidgetItem('begin')) self.tableTime.setItem(0, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(1, 0, QTableWidgetItem('end')) self.tableTime.setItem(1, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(2, 0, QTableWidgetItem('duration')) self.tableTime.setItem(2, 1, QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QtGui.QTableWidget(max_arg_num, 2) self.tableArgs.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_arg_num): self.tableArgs.setItem(idx, 0, QTableWidgetItem()) self.tableArgs.setItem(idx, 1, QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QtGui.QTableWidget(max_ret_num, 2) self.tableRet.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_ret_num): self.tableRet.setItem(idx, 0, QTableWidgetItem()) self.tableRet.setItem(idx, 1, QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect( self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)
def _init_cfg_options_tab(self, tab): resolve_indirect_jumps = QCheckBox(self) resolve_indirect_jumps.setText('Resolve indirect jumps') resolve_indirect_jumps.setChecked(True) self.option_widgets['resolve_indirect_jumps'] = resolve_indirect_jumps collect_data_refs = QCheckBox(self) collect_data_refs.setText( 'Collect cross-references and infer data types') collect_data_refs.setChecked(True) self.option_widgets['collect_data_refs'] = collect_data_refs layout = QVBoxLayout() layout.addWidget(resolve_indirect_jumps) layout.addWidget(collect_data_refs) layout.addStretch(0) frame = QFrame(self) frame.setLayout(layout) tab.addTab(frame, 'CFG Options')
class beso_gui(QDialog): def __init__(self): super().__init__() self.title = 'BESO Topology Optimization (experimental)' self.left = 250 self.top = 30 self.width = 550 self.height = 730 beso_gui.inp_file = "" beso_gui.beso_dir = os.path.dirname(__file__) self.initUI() # def closeEvent(self, event): # self.close() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Select analysis file button button = QPushButton('Select analysis file', self) button.setToolTip('*.inp CalculiX analysis file.') button.move(10, 10) button.clicked.connect(self.on_click) # Text box - file path and name self.textbox_file_name = QLineEdit(self) self.textbox_file_name.move(120, 15) self.textbox_file_name.resize(420, 20) self.textbox_file_name.setText("None analysis file selected") self.textbox_file_name.setToolTip('Analysis file.') # Update button button1 = QPushButton('Update domains', self) button1.setToolTip( 'Update naming inputs and material data from FreeCAD.') button1.move(10, 50) button1.clicked.connect(self.on_click1) # Domains definition # Label above domains definition label21 = QLabel('Domain 0', self) label21.setStyleSheet("font-weight: bold") label21.move(120, 50) label21 = QLabel('Domain 1', self) label21.setStyleSheet("font-weight: bold") label21.move(260, 50) label21 = QLabel('Domain 2', self) label21.setStyleSheet("font-weight: bold") label21.move(400, 50) label24 = QLabel('Material object', self) label24.move(20, 80) label25 = QLabel('Thickness object', self) label25.move(20, 110) label26 = QLabel('As design domain', self) label26.move(20, 140) label27 = QLabel('Stress limit [MPa]', self) label27.move(20, 170) # Combo box - select domain by material object self.combo = QComboBox(self) self.combo.setToolTip('Material object to define the domain.') self.combo.move(120, 80) self.combo.resize(140, 30) self.combo.currentIndexChanged.connect(self.on_change) self.combo1 = QComboBox(self) self.combo1.setToolTip('Material object to define the domain.') self.combo1.move(260, 80) self.combo1.resize(140, 30) self.combo1.currentIndexChanged.connect(self.on_change1) self.combo2 = QComboBox(self) self.combo2.setToolTip('Material object to define the domain.') self.combo2.move(400, 80) self.combo2.resize(140, 30) self.combo2.currentIndexChanged.connect(self.on_change2) # Combo box - select thickness object self.combo0t = QComboBox(self) self.combo0t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo0t.move(120, 110) self.combo0t.resize(140, 30) self.combo1t = QComboBox(self) self.combo1t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo1t.move(260, 110) self.combo1t.resize(140, 30) self.combo2t = QComboBox(self) self.combo2t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo2t.move(400, 110) self.combo2t.resize(140, 30) self.textbox3 = QLineEdit(self) self.textbox3.move(120, 170) self.textbox3.resize(40, 20) # self.textbox3.setText("") self.textbox3.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox4 = QLineEdit(self) self.textbox4.move(260, 170) self.textbox4.resize(40, 20) # self.textbox4.setText("") self.textbox4.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox5 = QLineEdit(self) self.textbox5.move(400, 170) self.textbox5.resize(40, 20) # self.textbox5.setText("") self.textbox5.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') # Check box - design or nondesign self.checkbox = QCheckBox('', self) self.checkbox.setChecked(True) self.checkbox.setToolTip('Check to be the design domain.') self.checkbox.move(120, 140) self.checkbox1 = QCheckBox('', self) self.checkbox1.setChecked(True) self.checkbox1.setToolTip('Check to be the design domain.') self.checkbox1.move(260, 140) self.checkbox2 = QCheckBox('', self) self.checkbox2.setChecked(True) self.checkbox2.setToolTip('Check to be the design domain.') self.checkbox2.move(400, 140) # Text box - stress limit self.textbox = QLineEdit(self) self.textbox.move(120, 170) self.textbox.resize(40, 20) # self.textbox.setText("") self.textbox.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox1 = QLineEdit(self) self.textbox1.move(260, 170) self.textbox1.resize(40, 20) # self.textbox1.setText("") self.textbox1.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox2 = QLineEdit(self) self.textbox2.move(400, 170) self.textbox2.resize(40, 20) # self.textbox2.setText("") self.textbox2.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) # Filters # Label above filter definition label31 = QLabel('Filter 0', self) label31.setStyleSheet("font-weight: bold") label31.move(120, 210) label32 = QLabel('Filter 1', self) label32.setStyleSheet("font-weight: bold") label32.move(260, 210) label33 = QLabel('Filter 2', self) label33.setStyleSheet("font-weight: bold") label33.move(400, 210) label34 = QLabel('Type', self) label34.move(20, 240) label35 = QLabel('Range [mm]', self) label35.move(20, 270) label36 = QLabel('Direction vector', self) label36.move(20, 300) label37 = QLabel('Apply to', self) label37.move(20, 330) # Combo box - select filter type self.combo6 = QComboBox(self) self.combo6.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo6.addItem("None") self.combo6.addItem("simple") self.combo6.addItem("casting") self.combo6.setCurrentIndex(1) self.combo6.move(120, 240) self.combo6.currentIndexChanged.connect(self.on_change6) self.combo7 = QComboBox(self) self.combo7.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo7.addItem("None") self.combo7.addItem("simple") self.combo7.addItem("casting") self.combo7.move(260, 240) self.combo7.currentIndexChanged.connect(self.on_change7) self.combo8 = QComboBox(self) self.combo8.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo8.addItem("None") self.combo8.addItem("simple") self.combo8.addItem("casting") self.combo8.move(400, 240) self.combo8.currentIndexChanged.connect(self.on_change8) # Text box - filter range self.textbox6 = QLineEdit(self) self.textbox6.move(120, 270) self.textbox6.resize(50, 20) # self.textbox6.setText("") self.textbox6.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7 = QLineEdit(self) self.textbox7.move(260, 270) self.textbox7.resize(50, 20) # self.textbox7.setText("") self.textbox7.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7.setEnabled(False) self.textbox8 = QLineEdit(self) self.textbox8.move(400, 270) self.textbox8.resize(50, 20) # self.textbox8.setText("") self.textbox8.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox8.setEnabled(False) # Text box - casting direction self.textbox9 = QLineEdit(self) self.textbox9.move(120, 300) self.textbox9.resize(80, 20) self.textbox9.setText("0, 0, 1") self.textbox9.setEnabled(False) self.textbox9.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox10 = QLineEdit(self) self.textbox10.move(260, 300) self.textbox10.resize(80, 20) self.textbox10.resize(80, 20) self.textbox10.setText("0, 0, 1") self.textbox10.setEnabled(False) self.textbox10.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox11 = QLineEdit(self) self.textbox11.move(400, 300) self.textbox11.resize(80, 20) self.textbox11.setText("0, 0, 1") self.textbox11.setEnabled(False) self.textbox11.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') # list widget - select domains self.widget = QListWidget(self) self.widget.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget.move(120, 330) self.widget.resize(140, 120) self.widget.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1 = QListWidget(self) self.widget1.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget1.move(260, 330) self.widget1.resize(140, 120) self.widget1.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1.setEnabled(False) self.widget2 = QListWidget(self) self.widget2.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget2.move(400, 330) self.widget2.resize(140, 120) self.widget2.setSelectionMode(QAbstractItemView.MultiSelection) self.widget2.setEnabled(False) # Other settings label40 = QLabel('Other settings', self) label40.setStyleSheet("font-weight: bold") label40.move(10, 470) # AR, RR slider label41 = QLabel('Change per iteration: low', self) label41.setFixedWidth(150) label41.move(10, 500) label42 = QLabel('high', self) label42.move(240, 500) self.slider = QSlider(Qt.Horizontal, self) self.slider.setRange(1, 3) self.slider.setSingleStep(1) self.slider.setValue(2) self.slider.move(150, 500) self.slider.resize(80, 30) self.slider.setToolTip( 'Sets mass change per iteration, which is controlled as\n' 'slow: mass_addition_ratio=0.01, mass_removal_ratio=0.02\n' 'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n' 'fast: mass_addition_ratio=0.03, mass_removal_ratio=0.06') # optimization base combobox label51 = QLabel('Optimization base', self) label51.move(10, 530) self.combo51 = QComboBox(self) self.combo51.setToolTip( 'Basic principle to determine if element should remain or be removed:\n' '"stiffness" to maximize stiffness (minimize compliance),\n' '"heat" to maximize heat flow.') self.combo51.addItem("stiffness") self.combo51.addItem("heat") self.combo51.move(120, 530) # mass goal ratio label52 = QLabel('Mass goal ratio', self) label52.move(10, 560) self.textbox52 = QLineEdit(self) self.textbox52.move(120, 560) self.textbox52.resize(50, 20) self.textbox52.setText("0.4") self.textbox52.setToolTip( 'Fraction of all design domains masses to be achieved;\n' 'between 0 and 1.') # generate conf. file button button21 = QPushButton('Generate conf. file', self) button21.setToolTip( 'Writes configuration file with optimization parameters.') button21.move(10, 600) button21.clicked.connect(self.on_click21) # edit conf. file button button22 = QPushButton('Edit conf. file', self) button22.setToolTip('Opens configuration file for hand modifications.') button22.move(10, 630) button22.clicked.connect(self.on_click22) # run optimization button button23 = QPushButton('Run optimization', self) button23.setToolTip('Writes configuration file and runs optimization.') button23.move(10, 660) button23.clicked.connect(self.on_click23) # generate conf file and run optimization button button24 = QPushButton('Generate conf.\nfile and run\noptimization', self) button24.setToolTip('Writes configuration file and runs optimization.') button24.move(120, 600) button24.resize(100, 90) button24.clicked.connect(self.on_click24) # help buttons label41 = QLabel('Help', self) label41.move(440, 560) button31 = QPushButton('Example', self) button31.setToolTip( 'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD') button31.move(440, 590) # button31.resize(80, 50) button31.clicked.connect(self.on_click31) button32 = QPushButton('Conf. comments', self) button32.setToolTip( 'https://github.com/fandaL/beso/blob/master/beso_conf.py') button32.move(440, 620) # button32.resize(80, 50) button32.clicked.connect(self.on_click32) button33 = QPushButton('Close', self) button33.move(440, 690) # button33.resize(80, 50) button33.clicked.connect(self.on_click33) # open log file button40 = QPushButton('Open log file', self) button40.setToolTip('Opens log file in your text editor.\n' '(Does not refresh automatically.)') button40.move(10, 690) button40.clicked.connect(self.on_click40) self.on_click1() # first update self.show() # @pyqtSlot() def on_click(self): ex2 = SelectFile() self.show() self.textbox_file_name.setText(self.inp_file) def on_click1(self): # get material objects self.materials = [] self.thicknesses = [] for obj in App.ActiveDocument.Objects: if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]: self.materials.append(obj) elif obj.Name[:17] == "ElementGeometry2D": self.thicknesses.append(obj) # update materials combo boxes self.combo.clear() self.combo.addItem("None") self.combo1.clear() self.combo1.addItem("None") self.combo2.clear() self.combo2.addItem("None") self.combo0t.clear() self.combo0t.addItem("None") self.combo1t.clear() self.combo1t.addItem("None") self.combo2t.clear() self.combo2t.addItem("None") self.widget.clear() self.widget.addItem("All defined") self.widget.addItem("Domain 0") self.widget.addItem("Domain 1") self.widget.addItem("Domain 2") self.widget.setCurrentItem(self.widget.item(0)) self.widget1.clear() self.widget1.addItem("All defined") self.widget1.addItem("Domain 0") self.widget1.addItem("Domain 1") self.widget1.addItem("Domain 2") self.widget1.setCurrentItem(self.widget1.item(0)) self.widget2.clear() self.widget2.addItem("All defined") self.widget2.addItem("Domain 0") self.widget2.addItem("Domain 1") self.widget2.addItem("Domain 2") self.widget2.setCurrentItem(self.widget2.item(0)) for mat in self.materials: self.combo.addItem(mat.Label) self.combo1.addItem(mat.Label) self.combo2.addItem(mat.Label) if self.materials: self.combo.setCurrentIndex(1) for th in self.thicknesses: self.combo0t.addItem(th.Label) self.combo1t.addItem(th.Label) self.combo2t.addItem(th.Label) def on_click21(self): """Overwrite beso_conf.py file in the macro directory""" file_name = os.path.split(self.textbox_file_name.text())[1] path = os.path.split(self.textbox_file_name.text())[0] fea = ccxtools.FemToolsCcx() fea.setup_ccx() path_calculix = fea.ccx_binary optimization_base = self.combo51.currentText() elset_id = self.combo.currentIndex() - 1 thickness_id = self.combo0t.currentIndex() - 1 if elset_id != -1: if thickness_id != -1: elset = self.materials[elset_id].Name + self.thicknesses[ thickness_id].Name else: # 0 means None thickness selected elset = self.materials[elset_id].Name + "Solid" modulus = float( self.materials[elset_id].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id].Name) poisson = float( self.materials[elset_id].Material["PoissonRatio"].split()[0]) try: density = float(self.materials[elset_id].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: density = 0. try: conductivity = float( self.materials[elset_id].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: conductivity = 0. try: if self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion = float(self.materials[elset_id]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion = float( self.materials[elset_id]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: expansion = 0. try: specific_heat = float( self.materials[elset_id].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: specific_heat = 0. if thickness_id != -1: thickness = str( self.thicknesses[thickness_id].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id].Name) else: thickness = 0. optimized = self.checkbox.isChecked() if self.textbox.text(): von_mises = float(self.textbox.text()) else: von_mises = 0. elset_id1 = self.combo1.currentIndex() - 1 thickness_id1 = self.combo0t.currentIndex() - 1 if elset_id1 != -1: if thickness_id1 != -1: elset1 = self.materials[elset_id1].Name + self.thicknesses[ thickness_id1].Name else: # 0 means None thickness selected elset1 = self.materials[elset_id1].Name + "Solid" modulus1 = float( self.materials[elset_id1].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id1].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) poisson1 = float( self.materials[elset_id1].Material["PoissonRatio"].split()[0]) try: density1 = float(self.materials[elset_id1].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id1].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: density1 = 0. try: conductivity1 = float( self.materials[elset_id1].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id1].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: conductivity1 = 0. try: if self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion1 = float(self.materials[elset_id1]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion1 = float( self.materials[elset_id1]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: expansion1 = 0. try: specific_heat1 = float( self.materials[elset_id1].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id1].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: specific_heat1 = 0. if thickness_id1 != -1: thickness1 = str( self.thicknesses[thickness_id1].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id1].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id1].Name) else: thickness1 = 0. optimized1 = self.checkbox1.isChecked() if self.textbox1.text(): von_mises1 = float(self.textbox1.text()) else: von_mises1 = 0. elset_id2 = self.combo2.currentIndex() - 1 thickness_id2 = self.combo0t.currentIndex() - 1 if elset_id2 != -1: if thickness_id2 != -1: elset2 = self.materials[elset_id2].Name + self.thicknesses[ thickness_id2].Name else: # 0 means None thickness selected else2t = self.materials[elset_id2].Name + "Solid" modulus2 = float( self.materials[elset_id2].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id2].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) poisson2 = float( self.materials[elset_id2].Material["PoissonRatio"].split()[0]) try: density2 = float(self.materials[elset_id2].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id2].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: density2 = 0. try: conductivity2 = float( self.materials[elset_id2].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id2].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: conductivity2 = 0. try: if self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion2 = float(self.materials[elset_id2]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion2 = float( self.materials[elset_id2]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: expansion2 = 0. try: specific_heat2 = float( self.materials[elset_id2].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id2].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: specific_heat2 = 0. if thickness_id2 != -1: thickness2 = str( self.thicknesses[thickness_id2].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id2].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id2].Name) else: thickness2 = 0. optimized2 = self.checkbox2.isChecked() if self.textbox2.text(): von_mises2 = float(self.textbox2.text()) else: von_mises2 = 0. with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f: f.write( "# This is the configuration file with input parameters. It will be executed as python commands\n" ) f.write("# Written by beso_fc_gui.py at {}\n".format( datetime.datetime.now())) f.write("\n") f.write("path_calculix = '{}'\n".format(path_calculix)) f.write("path = '{}'\n".format(path)) f.write("file_name = '{}'\n".format(file_name)) f.write("\n") if elset_id != -1: f.write("elset_name = '{}'\n".format(elset)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density * 1e-6, density)) if thickness: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness, thickness)) if von_mises: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus * 1e-6, poisson, density * 1e-6, conductivity * 1e-6, expansion * 1e-6, specific_heat * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus, poisson, density, conductivity, expansion, specific_heat)) f.write("\n") if elset_id1 != -1: f.write("elset_name = '{}'\n".format(elset1)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized1)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density1 * 1e-6, density1)) if thickness1: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness1, thickness1)) if von_mises1: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises1 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises1)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus1 * 1e-6, poisson1, density1 * 1e-6, conductivity1 * 1e-6, expansion1 * 1e-6, specific_heat1 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n" "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n". format(modulus1, poisson1, density1, conductivity1, expansion1, specific_heat1)) f.write("\n") if elset_id2 != -1: f.write("elset_name = '{}'\n".format(elset2)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized2)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density2 * 1e-6, density2)) if thickness2: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness2, thickness2)) if von_mises2: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises2 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises2)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus2 * 1e-6, poisson2, density2 * 1e-6, conductivity2 * 1e-6, expansion2 * 1e-6, specific_heat2 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus2, poisson2, density2, conductivity2, expansion2, specific_heat2)) f.write("\n") f.write("mass_goal_ratio = " + self.textbox52.text()) f.write("\n") f.write("filter_list = [") filter = self.combo6.currentText() range = self.textbox6.text() direction = self.textbox9.text() selection = [item.text() for item in self.widget.selectedItems()] filter_domains = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains.append(elset) if "Domain 1" in selection: filter_domains.append(elset1) if "Domain 2" in selection: filter_domains.append(elset2) if filter == "simple": f.write("['simple', {}".format(range)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") elif filter == "casting": f.write("['casting', {}, ({})".format(range, direction)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") filter1 = self.combo7.currentText() range1 = self.textbox7.text() direction1 = self.textbox10.text() selection = [item.text() for item in self.widget1.selectedItems()] filter_domains1 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains1.append(elset) if "Domain 1" in selection: filter_domains1.append(elset1) if "Domain 2" in selection: filter_domains1.append(elset2) if filter1 == "simple": f.write(" ['simple', {}".format(range1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") elif filter1 == "casting": f.write(" ['casting', {}, ({})".format( range1, direction1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") filter2 = self.combo8.currentText() range2 = self.textbox8.text() direction2 = self.textbox11.text() selection = [item.text() for item in self.widget2.selectedItems()] filter_domains2 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains2.append(elset) if "Domain 1" in selection: filter_domains2.append(elset1) if "Domain 2" in selection: filter_domains2.append(elset2) if filter2 == "simple": f.write(" ['simple', {}".format(range2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") elif filter2 == "casting": f.write(" ['casting', {}, ({})".format( range2, direction2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") f.write(" ]\n") f.write("\n") f.write("optimization_base = '{}'\n".format(optimization_base)) f.write("\n") slider_position = self.slider.value() if slider_position == 1: f.write("mass_addition_ratio = 0.01\n") f.write("mass_removal_ratio = 0.02\n") if slider_position == 2: f.write("mass_addition_ratio = 0.015\n") f.write("mass_removal_ratio = 0.03\n") if slider_position == 3: f.write("mass_addition_ratio = 0.03\n") f.write("mass_removal_ratio = 0.06\n") f.write("ratio_type = 'relative'\n") f.write("\n") def on_click22(self): """Open beso_conf.py in FreeCAD editor""" FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py")) def on_click23(self): """"Run optimization""" # run in own thread (not freezing FreeCAD): needs also to comment "plt.show()" on the end of beso_main.py # self.optimization_thread = RunOptimization("beso_main") # self.optimization_thread.start() # run in foreground (freeze FreeCAD) exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read()) def on_click24(self): self.on_click21() # generate beso_conf.py self.on_click23() # run optimization def on_click31(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD") def on_click32(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/blob/master/beso_conf.py") def on_click33(self): self.close() def on_click40(self): """Open log file""" if self.textbox_file_name.text() in [ "None analysis file selected", "" ]: print("None analysis file selected") else: log_file = os.path.normpath(self.textbox_file_name.text()[:-4] + ".log") webbrowser.open(log_file) def on_change(self): if self.combo.currentText() == "None": self.combo0t.setEnabled(False) self.checkbox.setEnabled(False) self.textbox.setEnabled(False) else: self.combo0t.setEnabled(True) self.checkbox.setEnabled(True) self.textbox.setEnabled(True) def on_change1(self): if self.combo1.currentText() == "None": self.combo1t.setEnabled(False) self.checkbox1.setEnabled(False) self.textbox1.setEnabled(False) else: self.combo1t.setEnabled(True) self.checkbox1.setEnabled(True) self.textbox1.setEnabled(True) def on_change2(self): if self.combo2.currentText() == "None": self.combo2t.setEnabled(False) self.checkbox2.setEnabled(False) self.textbox2.setEnabled(False) else: self.combo2t.setEnabled(True) self.checkbox2.setEnabled(True) self.textbox2.setEnabled(True) def on_change6(self): if self.combo6.currentText() == "None": self.textbox6.setEnabled(False) self.textbox9.setEnabled(False) self.widget.setEnabled(False) elif self.combo6.currentText() == "casting": self.textbox6.setEnabled(True) self.textbox9.setEnabled(True) self.widget.setEnabled(True) else: self.textbox6.setEnabled(True) self.textbox9.setEnabled(False) self.widget.setEnabled(True) def on_change7(self): if self.combo7.currentText() == "None": self.textbox7.setEnabled(False) self.textbox10.setEnabled(False) self.widget1.setEnabled(False) elif self.combo7.currentText() == "casting": self.textbox7.setEnabled(True) self.textbox10.setEnabled(True) self.widget1.setEnabled(True) else: self.textbox7.setEnabled(True) self.textbox10.setEnabled(False) self.widget1.setEnabled(True) def on_change8(self): if self.combo8.currentText() == "None": self.textbox8.setEnabled(False) self.textbox11.setEnabled(False) self.widget2.setEnabled(False) elif self.combo8.currentText() == "casting": self.textbox8.setEnabled(True) self.textbox11.setEnabled(True) self.widget2.setEnabled(True) else: self.textbox8.setEnabled(True) self.textbox11.setEnabled(False) self.widget2.setEnabled(True)
class MassAttribute_UI(QDialog): """ The main UI """ class Applikator(QObject): """ This is the core applier which toggle the display of the corresponding widget and handling events' connections """ def __init__(self, parent=None): super(MassAttribute_UI.Applikator, self).__init__() self.root = parent def widget_event(self, t): """ Return the correct widget's event depending on attribute's type :param t: the attribute's type :type t: str :return: the event :rtype : Signal """ return { 'float': self.root.W_EDI_float.valueChanged, 'enum': self.root.W_EDI_enum.currentIndexChanged, 'int': self.root.W_EDI_int.valueChanged, 'bool': self.root.W_EDI_bool.stateChanged, 'str': self.root.W_EDI_str.textChanged, 'd3': self.root.W_EDI_d3.valuesChanged, 'd4': self.root.W_EDI_d4.valuesChanged, 'color': self.root.W_EDI_color.colorChanged }[t] def unset_editors(self): """ Toggle off all editors and disconnect the current one """ for widget in (self.root.W_EDI_float, self.root.W_EDI_int, self.root.W_EDI_enum, self.root.W_EDI_bool, self.root.W_EDI_str, self.root.W_EDI_d3, self.root.W_EDI_d4, self.root.W_EDI_color): widget.setVisible(False) # trying to force disconnection try: self.widget_event(self.root.ctx).disconnect( self.root.apply_value) except (KeyError, RuntimeError): pass def prepare(applier_name): """ A decorator to prepare the attribute depending on type for the corresponding widget and getting the attribute's value :param applier_name: attribute's type :type applier_name: str """ def sub_wrapper(func): def wrapper(self, attr_path): self.unset_editors() self.root.ctx = applier_name self.root.__getattribute__('W_EDI_%s' % applier_name).setVisible(True) ret = func(self, cmds.getAttr(attr_path), attr_path) return ret return wrapper return sub_wrapper @staticmethod def get_bounds(obj, attr, min_default, max_default): """ Try to retrieve the range for the given attribute, if min or max fail it'll set default values :param obj: the object's name :type obj: str :param attr: attribute's name :type attr: str :param min_default: minimum default value :param max_default: max default value :type min_default: float | int :type max_default: float | int :return: minimum, maximum :rtype : tuple """ try: assert cmds.attributeQuery(attr, n=obj, mxe=True) maxi = cmds.attributeQuery(attr, n=obj, max=True)[0] except (RuntimeError, AssertionError): maxi = max_default try: assert cmds.attributeQuery(attr, n=obj, mne=True) mini = cmds.attributeQuery(attr, n=obj, min=True)[0] except (RuntimeError, AssertionError): mini = min_default return mini, maxi @prepare('float') def apply_float(self, value, path): """ Float attribute case :param value: attribute's value :param path: attribute's path = obj.attr """ obj, attr = path.split('.', 1) self.root.W_EDI_float.setRange( *self.get_bounds(obj, attr, -100.0, 100.0)) self.root.W_EDI_float.setValue(value) @prepare('enum') def apply_enum(self, value, path): """Enum case""" self.root.W_EDI_enum.clear() obj, attr = path.split('.', 1) try: enums = [ enum.split('=')[0] for enum in cmds.attributeQuery( attr, n=obj, listEnum=True)[0].split(':') ] except RuntimeError: self.apply_int(path) else: self.root.W_EDI_enum.addItems(enums) self.root.W_EDI_enum.setCurrentIndex( enums.index(cmds.getAttr(path, asString=True))) @prepare('int') def apply_int(self, value, path): """Integer case""" obj, attr = path.split('.', 1) self.root.W_EDI_int.setRange( *self.get_bounds(obj, attr, -1000, 1000)) self.root.W_EDI_int.setValue(value) @prepare('bool') def apply_bool(self, value, path): """Boolean case""" self.root.W_EDI_bool.setChecked(value) self.root.W_EDI_bool.setText(path.split('.', 1)[1]) @prepare('str') def apply_str(self, value, path): """String case""" self.root.W_EDI_str.setText(value) @prepare('d3') def apply_d3(self, value, path): """3D array case""" self.root.W_EDI_d3.setValues(value[0]) @prepare('d4') def apply_d4(self, value, path): """4D array case""" self.root.W_EDI_d4.setValues(value[0]) @prepare('color') def apply_color(self, value, path): """Color case""" try: colors = value[0] self.root.W_EDI_color.setColor([int(c * 255) for c in colors]) except TypeError: self.apply_int(value, path) class Attribute(str): """ A custom string attribute class to ship more information into the string variable """ def __new__(cls, path='', super_type=Object): obj, attr = path.split('.', 1) str_obj = str.__new__(cls, attr) str_obj.obj, str_obj.attr = obj, attr str_obj.path = path str_obj.super_type = super_type str_obj.type = None return str_obj # static variables to pre-load icons and attributes short names ctx_icons = { 'float': QIcon(':render_decomposeMatrix.png'), 'enum': QIcon(':showLineNumbers.png'), 'bool': QIcon(':out_decomposeMatrix.png'), 'time': QIcon(':time.svg'), 'byte': QIcon(':out_defaultTextureList.png'), 'angle': QIcon(':angleDim.png'), 'string': QIcon(':text.png'), 'float3': QIcon(':animCurveTA.svg'), 'float4': QIcon(':animCurveTA.svg'), 'color': QIcon(':clampColors.svg') } for ctx in ('doubleLinear', 'double', 'long', 'short'): ctx_icons[ctx] = ctx_icons['float'] ctx_icons['double3'] = ctx_icons['float3'] ctx_icons['double4'] = ctx_icons['float4'] ctx_wide = { 'float': ('float', 'doubleLinear', 'double', 'long', 'short'), 'enum': ('enum', ), 'bool': ('bool', ), 'time': ('time', ), 'byte': ('byte', ), 'angle': ('doubleAngle', ), 'string': ('string', ), 'float3': ('double3', 'float3'), 'float4': ('double4', 'float4'), 'color': ('color', ) } def __init__(self, parent=None): super(MassAttribute_UI, self).__init__(parent) # Abstract self.applier = self.Applikator(self) self.selection = [] self.callback = None self.ctx = None # storing found attributes' types to avoid double check self.solved = {} self.setLocale(QLocale.C) self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_QuitOnClose) self.setFixedWidth(300) self.setWindowTitle('Massive Attribute Modifier') # UI L_main = QVBoxLayout() self.WV_title = QLabel('') self.WV_title.setVisible(False) self.WV_title.setFont(QFont('Verdana', 10)) self.WV_title.setContentsMargins(0, 0, 0, 7) self.WB_select = QPushButton('Select') self.WB_select.setVisible(False) self.WB_select.setFixedWidth(50) self.WB_select.clicked.connect(lambda: cmds.select(self.selection)) self.WB_update = QPushButton('Update') self.WB_update.setFixedWidth(50) self.WB_update.clicked.connect( lambda: self.update_attributes(cmds.ls(sl=True))) self.WV_search = Filter() self.WV_search.textChanged.connect(self.filter) self.WC_cases = QCheckBox('Case sensitive') self.WC_cases.stateChanged.connect(self.filter) self.WC_types = QCheckBox('Type filtering') self.WL_attrtype = QComboBox() self.WL_attrtype.setEnabled(False) for i, ctx in enumerate(sorted(self.ctx_wide)): self.WL_attrtype.addItem(ctx.title()) self.WL_attrtype.setItemIcon(i, self.ctx_icons[ctx]) L_attrtype = line(self.WC_types, self.WL_attrtype) self.WC_types.stateChanged.connect( partial(self.update_attributes, self.selection)) self.WC_types.stateChanged.connect(self.WL_attrtype.setEnabled) self.WL_attrtype.currentIndexChanged.connect(self.filter) self.WC_liveu = QCheckBox('Live') self.WC_liveu.stateChanged.connect(self.WB_update.setDisabled) self.WC_liveu.stateChanged.connect(self.set_callback) self.WC_histo = QCheckBox('Load history') self.WC_histo.setChecked(True) self.WC_histo.stateChanged.connect( partial(self.update_attributes, self.selection)) self.WC_child = QCheckBox('Children') self.WC_child.stateChanged.connect( partial(self.update_attributes, self.selection)) options = group( 'Options', line(self.WC_cases, L_attrtype), line(self.WC_child, self.WC_histo, self.WC_liveu, self.WB_update)) options.layout().setSpacing(2) self.WL_attributes = QTreeWidget() self.WL_attributes.setStyleSheet( 'QTreeView {alternate-background-color: #1b1b1b;}') self.WL_attributes.setAlternatingRowColors(True) self.WL_attributes.setHeaderHidden(True) self.WL_attributes.setRootIsDecorated(False) self.objs_attr = set() self.shps_attr = set() self.W_EDI_float = FloatBox() self.W_EDI_int = IntBox() self.W_EDI_enum = QComboBox() self.W_EDI_bool = QCheckBox() self.W_EDI_str = QLineEdit() self.W_EDI_d3 = Double3() self.W_EDI_d4 = Double4() self.W_EDI_color = ColorPicker() # Final layout L_title = line(self.WV_title, self.WB_select) L_title.setStretch(0, 1) L_main.addLayout(L_title) L_main.setAlignment(Qt.AlignLeft) L_main.addWidget(self.WV_search) L_main.addWidget(options) L_main.addWidget(self.WL_attributes) L_edits = col(self.W_EDI_bool, self.W_EDI_int, self.W_EDI_float, self.W_EDI_enum, self.W_EDI_str, self.W_EDI_d3, self.W_EDI_d4, self.W_EDI_color) L_edits.setContentsMargins(0, 8, 0, 0) L_main.addLayout(L_edits) L_main.setStretch(3, 1) L_main.setSpacing(2) self.appliers = { 'float': self.applier.apply_float, 'enum': self.applier.apply_enum, 'bool': self.applier.apply_bool, 'time': self.applier.apply_float, 'byte': self.applier.apply_int, 'angle': self.applier.apply_float, 'string': self.applier.apply_str, 'float3': self.applier.apply_d3, 'float4': self.applier.apply_d4, 'color': self.applier.apply_color } self.setLayout(L_main) # final settings self.WL_attributes.itemSelectionChanged.connect(self.update_setter) self.applier.unset_editors() def closeEvent(self, *args, **kwargs): self.set_callback(False) def set_callback(self, state): """ Toggle selection event callback :param state: checkbox's state :type state: bool | int """ if state and not self.callback: self.callback = MEventMessage.addEventCallback( 'SelectionChanged', self.update_attributes) self.update_attributes(cmds.ls(sl=True)) elif not state and self.callback: MMessage.removeCallback(self.callback) self.callback = None @staticmethod def format_title(nodes): """ Extract the matching characters from a given nodes selection, if begin matches it will return "joint*" with a wildcard when names don't match :param nodes: objects' list :type nodes: list | tuple :return: the formatted name with the corresponding characters :rtype : str """ res = None if nodes: # we get the first node as a reference node = nodes[0] # and compare with the other nodes subs = [w for w in nodes if w != node] l = 1 valid = True # will continue until l (length) match the full name's length or until names don't match while l < len(node) and valid: for sub in subs: if not sub.startswith(node[:l]): valid = False break else: l += 1 # if matching characters isn't long enough we only display the number of nodes selected if l <= 3: res = '%i objects' % len(nodes) # otherwise showing matching pattern elif l < len(node) or len(nodes) > 1: res = node[:l - 1] + '* (%i objects)' % len(nodes) else: res = node return res @staticmethod def get_history(node): """ Extract history for the given node :rtype: list """ return cmds.listHistory(node, il=2, pdo=True) or [] @staticmethod def get_shapes(node): """ Extract shape(s) for the given node :rtype: list """ return cmds.listRelatives(node, s=True, ni=True, f=True) def get_attributes_type(self, attrs): """ For a given list of attributes of type Attribute, will loop through and fill the type parameter of the attribute with the corresponding type, if type is invalid or not handled, it'll remove it :param attrs: attributes' list :type attrs: [MassAttribute_UI.Attribute] :return: cleaned and filled attributes' list :rtype: [MassAttribute_UI.Attribute] """ attrs = list(attrs) # first we sort the attributes' list attrs.sort() # then we try to extract the attribute's type for i, attr in enumerate(attrs): try: if attr.attr in self.solved: attr.type = self.solved[attr.attr] raise RuntimeError tpe = cmds.getAttr(attr.path, typ=True) assert tpe attr.type = tpe self.solved[attr.attr] = tpe except (AssertionError, ValueError, RuntimeError): pass # defining a to-remove list rm_list = set() layers = {'3': 'XYZ', '4': 'XYZW'} for i, attr in enumerate(attrs): if i in rm_list: continue # we handle some special cases here, if ever the attribute list contains RGB and separate R, G and B we # assume it's a color, if it's a double3 or float3 and we find the corresponding XYZ, we remove then to # avoid duplicates if attr.endswith('RGB'): if '%sR' % attr[:-3] in attrs: attr.type = 'color' for chan in 'RGB': rm_list.add(attrs.index('%s%s' % (attr[:-3], chan))) # if the attribute's type isn't in the list, we remove elif attr.type not in MassAttribute_UI.ctx_icons: rm_list.add(i) elif attr.endswith('R'): if '%sG' % attr[:-1] in attrs and attr[:-1] in attrs: attr.type = 'color' for chan in 'RGB': rm_list.add(attrs.index('%s%s' % (attr[:-1], chan))) elif attr.type in ('double3', 'double4', 'float3', 'float4'): if '%sX' % attr in attrs: for chan in layers[attr.type[-1]]: rm_list.add(attrs.index('%s%s' % (attr, chan))) # finally cleaning the list for i in sorted(rm_list, reverse=True): attrs.pop(i) return attrs def apply_value(self, value): """ When the value is modified in the UI, we forward the given value and applies to the object's :param value: attribute's value, mixed type :type value: mixed """ # We get the only selected object in list and get it's super type (Shape, History or Object) and # type (float, int, string) item = self.WL_attributes.selectedItems()[0] attr = item.attribute shape = attr.super_type == Shape histo = attr.super_type == History tpe = item.attribute.type # eq dict for each context value = { 'bool': bool, 'int': int, 'float': float, 'enum': int, 'str': str, 'd3': list, 'd4': list, 'color': list }[self.ctx](value) # converting the selection into a set cmds.undoInfo(openChunk=True) targets = set(self.selection) # we propagate to children if 'Children' checkbox is on if self.WC_child.isChecked(): for obj in list(targets): targets |= set(cmds.listRelatives(obj, ad=True)) # if the target attribute is on the history, we add all selection's history to the list if histo: for obj in list(targets): targets.remove(obj) targets |= set(self.get_history(obj)) # then we loop through target objects for obj in targets: # if the target is on the shape we get object's shape if shape and not histo: shapes = self.get_shapes(obj) if obj in shapes: continue else: obj = shapes[0] # then we try to apply depending on attribute's type try: correct_path = attr.path.replace(attr.obj, obj) if tpe == 'string': cmds.setAttr(correct_path, value, type='string') elif tpe in ('double3', 'double4', 'float3', 'float4', 'color'): cmds.setAttr(correct_path, *value, type='double%d' % len(value)) else: cmds.setAttr(correct_path, value) except RuntimeError: pass cmds.undoInfo(closeChunk=True) def update_setter(self): """ When the list's selection changes we update the applier widget """ item = self.WL_attributes.selectedItems() # abort if no item is selected if not len(item): return # getting attribute's parameter attr = item[0].attribute if len(self.selection): try: # looping until we find a context having the current attribute's type for applier in self.ctx_wide: if attr.type in self.ctx_wide[applier]: break # then we apply for the given path (obj.attribute) self.appliers[applier](attr.path) # and connecting event to the self.apply_value function self.applier.widget_event(self.ctx).connect(self.apply_value) # otherwise selection or type is invalid except IndexError: self.ctx = None def update_attributes(self, selection=None, *args): """ Update the attributes for the given selection, looping through objects' attributes, finding attr in common between all objects then cleaning the lists, doing the same for shapes and / or histories :param selection: object's selection """ # redefining lists as set to intersect union etc self.objs_attr = set() self.shps_attr = set() # pre init self.WL_attributes.clear() self.applier.unset_editors() self.selection = selection or (cmds.ls( sl=True) if self.WC_liveu.isChecked() else self.selection) self.WV_title.setText(self.format_title(self.selection)) self.WV_title.setVisible(bool(len(self.selection))) self.WB_select.setVisible(bool(len(self.selection))) if not len(self.selection): return def get_usable_attrs(obj, super_type): """ Small internal function to get a compatible attributes' list for the given object and assign the given super_type to it (Object, Shape or History) :param obj: object's name :type obj: str :param super_type: attribute's main type :type super_type: Object | Shape | History :return: """ return set([ MassAttribute_UI.Attribute('%s.%s' % (obj, attr), super_type) for attr in cmds.listAttr( obj, se=True, ro=False, m=True, w=True) ]) if len(self.selection): self.objs_attr = get_usable_attrs(self.selection[0], Object) # if we also want the object's history we add it to the initial set if self.WC_histo.isChecked(): for histo in self.get_history(self.selection[0]): self.objs_attr |= get_usable_attrs(histo, History) # filling the shape's set for shape in (self.get_shapes(self.selection[0]) or []): self.shps_attr |= get_usable_attrs(shape, Shape) # if selection's length bigger than one we compare by intersection with the other sets if len(self.selection) > 1: for obj in self.selection: sub_attr = get_usable_attrs(obj, Object) if self.WC_histo.isChecked(): for histo in self.get_history(obj): sub_attr |= get_usable_attrs(histo, History) self.objs_attr.intersection_update(sub_attr) for shape in (self.get_shapes(self.selection[0]) or []): self.shps_attr.intersection_update( get_usable_attrs(shape, Shape)) # finally getting all intersecting attributes' types self.objs_attr = self.get_attributes_type(self.objs_attr) self.shps_attr = self.get_attributes_type(self.shps_attr) # and filtering the list self.filter() def add_set(self, iterable, title=None): """ Adding the given iterable to the list with a first Separator object with given title :param iterable: list of item's attributes :param title: Separator's name """ if len(iterable): # if title is given we first add a Separator item to indicate coming list title if title: self.WL_attributes.addTopLevelItem( QTreeWidget_Separator(title)) items = [] for attr in sorted(iterable): item = QTreeWidgetItem([attr]) # assigning the attribute itself inside a custom parameter item.attribute = attr items.append(item) # finally adding all the items to the list self.WL_attributes.addTopLevelItems(items) def filter(self): """ Filter the list with UI's parameters, such as name or type filtering, etc """ # pre cleaning self.WL_attributes.clear() # using regex compile to avoid re execution over many attributes mask = self.WV_search.text() case = 0 if self.WC_cases.isChecked() else re.IGNORECASE re_start = re.compile(r'^%s.*?' % mask, case) re_cont = re.compile(r'.*?%s.*?' % mask, case) # getting the four different lists obj_start = set([at for at in self.objs_attr if re_start.search(at)]) shp_start = set([at for at in self.shps_attr if re_start.search(at)]) # if type filtering is one we only extract the wanted attribute's type if self.WC_types.isChecked(): obj_start = set([ at for at in obj_start if at.type in self.ctx_wide[ self.WL_attrtype.currentText().lower()] ]) shp_start = set([ at for at in shp_start if at.type in self.ctx_wide[ self.WL_attrtype.currentText().lower()] ]) # finally adding the current sets if there is a mask we add the also the containing matches if mask: # getting contains filtering and type containers filtering obj_contains = obj_start.symmetric_difference( set([at for at in self.objs_attr if re_cont.search(at)])) shp_contains = shp_start.symmetric_difference( set([at for at in self.shps_attr if re_cont.search(at)])) if self.WC_types.isChecked(): obj_contains = set([ at for at in obj_contains if at.type in self.ctx_wide[ self.WL_attrtype.currentText().lower()] ]) shp_contains = set([ at for at in shp_contains if at.type in self.ctx_wide[ self.WL_attrtype.currentText().lower()] ]) # adding the sets self.add_set(obj_start, 'Obj attributes starting with') self.add_set(obj_contains, 'Obj attributes containing') self.add_set(shp_start, 'Shape attributes starting with') self.add_set(shp_contains, 'Shape attributes containing') else: self.add_set(obj_start, 'Object\'s attributes') self.add_set(shp_start, 'Shape\'s attributes') # and we select the first one if ever there is something in the list if self.WL_attributes.topLevelItemCount(): self.WL_attributes.setItemSelected( self.WL_attributes.topLevelItem(1), True)
class HotkeyDialogView(QDialog): HOTKEY_DIALOG_OK = "HOTKEY_DIALOG_OK" HOTKEY_DIALOG_CANCEL = "HOTKEY_DIALOG_CANCEL" def __init__(self, *args, **kwargs): super(HotkeyDialogView, self).__init__(*args, **kwargs) self.setWindowTitle("Set Hotkey") self.edit_line = QLineEdit() self.edit_line.setEnabled(False) self.installEventFilter(self) self.ok_btn = QPushButton("&Ok") # noinspection PyUnresolvedReferences self.ok_btn.clicked.connect(self.accept) self.control_check = QCheckBox() self.control_label = QLabel("CTRL") self.shift_check = QCheckBox() self.shift_label = QLabel("SHIFT") self.alt_check = QCheckBox() self.alt_label = QLabel("ALT") self.cancel_btn = QPushButton("&Cancel") # noinspection PyUnresolvedReferences self.cancel_btn.clicked.connect(self.reject) self.h_keys_layout = QHBoxLayout() self.h_btn_layout = QHBoxLayout() self.v_layout = QVBoxLayout() self.h_btn_layout.addStretch(0) self.h_btn_layout.addWidget(self.ok_btn) self.h_btn_layout.addWidget(self.cancel_btn) self.h_keys_layout.addWidget(self.control_check) self.h_keys_layout.addWidget(self.control_label) self.h_keys_layout.addWidget(self.shift_check) self.h_keys_layout.addWidget(self.shift_label) self.h_keys_layout.addWidget(self.alt_check) self.h_keys_layout.addWidget(self.alt_label) self.h_keys_layout.addWidget(self.edit_line) self.v_layout.addLayout(self.h_keys_layout) self.v_layout.addLayout(self.h_btn_layout) self.setLayout(self.v_layout) # noinspection PyUnresolvedReferences self.accepted.connect(self.on_accept) # noinspection PyUnresolvedReferences self.rejected.connect(self.on_reject) self.__key = None def eventFilter(self, source, event): """ @type event: QEvent.QEvent @return: """ if event.type() == QEvent.KeyPress: event = event """:type :QKeyEvent""" self.__key = event.key key_str = QKeySequence(event.key()).toString() if key_str == "Esc": self.edit_line.setText("") return True self.edit_line.setText(key_str) return True return QDialog.eventFilter(self, source, event) def on_accept(self): hotkey_str = "" key = self.edit_line.text() if key: if self.control_check.isChecked(): hotkey_str += "Ctrl+" if self.alt_check.isChecked(): hotkey_str += "Alt+" if self.shift_check.isChecked(): hotkey_str += "Shift+" hotkey_str += key if key == "": hotkey_str = "" Facade.getInstance().sendNotification( HotkeyDialogView.HOTKEY_DIALOG_OK, {"key_sequence": hotkey_str}) def on_reject(self): Facade.getInstance().sendNotification( HotkeyDialogView.HOTKEY_DIALOG_CANCEL, )
def __init__(self, parent=None): super(MassAttribute_UI, self).__init__(parent) # Abstract self.applier = self.Applikator(self) self.selection = [] self.callback = None self.ctx = None # storing found attributes' types to avoid double check self.solved = {} self.setLocale(QLocale.C) self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_QuitOnClose) self.setFixedWidth(300) self.setWindowTitle('Massive Attribute Modifier') # UI L_main = QVBoxLayout() self.WV_title = QLabel('') self.WV_title.setVisible(False) self.WV_title.setFont(QFont('Verdana', 10)) self.WV_title.setContentsMargins(0, 0, 0, 7) self.WB_select = QPushButton('Select') self.WB_select.setVisible(False) self.WB_select.setFixedWidth(50) self.WB_select.clicked.connect(lambda: cmds.select(self.selection)) self.WB_update = QPushButton('Update') self.WB_update.setFixedWidth(50) self.WB_update.clicked.connect( lambda: self.update_attributes(cmds.ls(sl=True))) self.WV_search = Filter() self.WV_search.textChanged.connect(self.filter) self.WC_cases = QCheckBox('Case sensitive') self.WC_cases.stateChanged.connect(self.filter) self.WC_types = QCheckBox('Type filtering') self.WL_attrtype = QComboBox() self.WL_attrtype.setEnabled(False) for i, ctx in enumerate(sorted(self.ctx_wide)): self.WL_attrtype.addItem(ctx.title()) self.WL_attrtype.setItemIcon(i, self.ctx_icons[ctx]) L_attrtype = line(self.WC_types, self.WL_attrtype) self.WC_types.stateChanged.connect( partial(self.update_attributes, self.selection)) self.WC_types.stateChanged.connect(self.WL_attrtype.setEnabled) self.WL_attrtype.currentIndexChanged.connect(self.filter) self.WC_liveu = QCheckBox('Live') self.WC_liveu.stateChanged.connect(self.WB_update.setDisabled) self.WC_liveu.stateChanged.connect(self.set_callback) self.WC_histo = QCheckBox('Load history') self.WC_histo.setChecked(True) self.WC_histo.stateChanged.connect( partial(self.update_attributes, self.selection)) self.WC_child = QCheckBox('Children') self.WC_child.stateChanged.connect( partial(self.update_attributes, self.selection)) options = group( 'Options', line(self.WC_cases, L_attrtype), line(self.WC_child, self.WC_histo, self.WC_liveu, self.WB_update)) options.layout().setSpacing(2) self.WL_attributes = QTreeWidget() self.WL_attributes.setStyleSheet( 'QTreeView {alternate-background-color: #1b1b1b;}') self.WL_attributes.setAlternatingRowColors(True) self.WL_attributes.setHeaderHidden(True) self.WL_attributes.setRootIsDecorated(False) self.objs_attr = set() self.shps_attr = set() self.W_EDI_float = FloatBox() self.W_EDI_int = IntBox() self.W_EDI_enum = QComboBox() self.W_EDI_bool = QCheckBox() self.W_EDI_str = QLineEdit() self.W_EDI_d3 = Double3() self.W_EDI_d4 = Double4() self.W_EDI_color = ColorPicker() # Final layout L_title = line(self.WV_title, self.WB_select) L_title.setStretch(0, 1) L_main.addLayout(L_title) L_main.setAlignment(Qt.AlignLeft) L_main.addWidget(self.WV_search) L_main.addWidget(options) L_main.addWidget(self.WL_attributes) L_edits = col(self.W_EDI_bool, self.W_EDI_int, self.W_EDI_float, self.W_EDI_enum, self.W_EDI_str, self.W_EDI_d3, self.W_EDI_d4, self.W_EDI_color) L_edits.setContentsMargins(0, 8, 0, 0) L_main.addLayout(L_edits) L_main.setStretch(3, 1) L_main.setSpacing(2) self.appliers = { 'float': self.applier.apply_float, 'enum': self.applier.apply_enum, 'bool': self.applier.apply_bool, 'time': self.applier.apply_float, 'byte': self.applier.apply_int, 'angle': self.applier.apply_float, 'string': self.applier.apply_str, 'float3': self.applier.apply_d3, 'float4': self.applier.apply_d4, 'color': self.applier.apply_color } self.setLayout(L_main) # final settings self.WL_attributes.itemSelectionChanged.connect(self.update_setter) self.applier.unset_editors()
def __init__(self, text, validator, minValue, maxValue ): QWidget.__init__( self ) layout = QHBoxLayout( self ) checkBox = QCheckBox() checkBox.setFixedWidth( 115 ) checkBox.setText( text ) layout.addWidget( checkBox ) hLayoutX = QHBoxLayout() lineEditXMin = QLineEdit() lineEditXMax = QLineEdit() hLayoutX.addWidget( lineEditXMin ) hLayoutX.addWidget( lineEditXMax ) lineEditXMin.setValidator( validator ) lineEditXMax.setValidator( validator ) lineEditXMin.setText( str( minValue ) ) lineEditXMax.setText( str( maxValue ) ) layout.addLayout( hLayoutX ) self.checkBox = checkBox self.lineEditX_min = lineEditXMin self.lineEditX_max = lineEditXMax self.lineEdits = [ lineEditXMin, lineEditXMax ] QtCore.QObject.connect( checkBox, QtCore.SIGNAL( "clicked()" ), self.updateEnabled ) self.updateEnabled()