def __init__(self, current_case): QWidget.__init__(self) self.__model = PlotCaseModel() self.__signal_mapper = QSignalMapper(self) self.__case_selectors = {} self.__case_selectors_order = [] layout = QVBoxLayout() add_button_layout = QHBoxLayout() button = QPushButton(util.resourceIcon("ide/small/add"), "Add case to plot") button.clicked.connect(self.addCaseSelector) add_button_layout.addStretch() add_button_layout.addWidget(button) add_button_layout.addStretch() layout.addLayout(add_button_layout) self.__case_layout = QVBoxLayout() self.__case_layout.setMargin(0) layout.addLayout(self.__case_layout) self.addCaseSelector(disabled=True, current_case=current_case) layout.addStretch() self.setLayout(layout) self.__signal_mapper.mapped[QWidget].connect(self.removeWidget)
def open_gui(self): self.main = MainWindow(self) self.main.setFixedSize(730, 430) self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png"))) self.tabs = QTabWidget() widget = QWidget() layout = QVBoxLayout() layout.addWidget(self.tabs) widget.setLayout(layout) self.main.setCentralWidget(widget) self.projects.append(ProjectEnvDisplay(self.tabs, self)) self.projects.append(ProjectStatistics(self.tabs, self)) self.projects.append(ProjectXively(self.tabs, self)) self.tabs.addTab(self.projects[0], "Display Environment Measurements") self.tabs.addTab(self.projects[1], "Show Statistics with Button Control") self.tabs.addTab(self.projects[2], "Connect to Xively") self.active_project = self.projects[0] self.tabs.currentChanged.connect(self.tabChangedSlot) self.main.setWindowTitle("Starter Kit: Weather Station Demo " + config.DEMO_VERSION) self.main.show()
def __init__(self, low, upp, parent=None): QWidget.__init__(self, parent) self.layout = QHBoxLayout(self) self._spin_start = QSpinBox(self) self._spin_end = QSpinBox(self) self.layout.addWidget(self._spin_start) self._slider = QxtSpanSlider(self) self._slider.setHandleMovementMode(QxtSpanSlider.NoOverlapping) self._slider.lowerPositionChanged.connect(lambda x: self._spin_start.setValue(x)) self._slider.upperPositionChanged.connect(lambda x: self._spin_end.setValue(x)) self._spin_start.valueChanged.connect( lambda x: self._slider.setLowerPosition(x) if x < self._slider.upperValue else self._spin_start.setValue(self._slider.upperValue - 1)) self._spin_end.valueChanged.connect( lambda x: self._slider.setUpperPosition(x) if x > self._slider.lowerValue else self._spin_end.setValue(self._slider.lowerValue + 1)) self.layout.addWidget(self._slider) self.layout.addWidget(self._spin_end) self.setRange(low, upp) self.setSpan(low, upp)
def __init__(self, *args): QWidget.__init__(self, *args) self._browser = QTextEdit(self) self._browser.setReadOnly(True) self._browser.document().setDefaultStyleSheet(self._browser.document().defaultStyleSheet() + "span {white-space:pre;}") editorClass = self._makeEditorClass() self._edit = editorClass(self, None, terminalWidget=True) lowLevelWidget = self._edit.focusProxy() if lowLevelWidget is None: lowLevelWidget = self._edit lowLevelWidget.installEventFilter(self) self._edit.newLineInserted.connect(self._onEditNewLine) self._edit.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) self.setFocusProxy(self._edit) layout = QVBoxLayout(self) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._browser) layout.addWidget(self._edit) self._history = [''] # current empty line self._historyIndex = 0 self._edit.setFocus()
def load(self): self.initTranslations() cfg = SimuVis4.Globals.config cfgsec = self.name.lower() if not cfg.has_section(cfgsec): cfg.add_section(cfgsec) cfg.set_def(cfgsec, 'set_default_backend', 'yes') cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721') cfg.set_def(cfgsec, 'mouse_wheel_step', '15') glb = SimuVis4.Globals import matplotlib if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion: SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \ (mplMinVersion, mplMaxVersion, matplotlib.__version__)) return False self.matplotlib = matplotlib if cfg.getboolean(cfgsec, 'set_default_backend'): try: sys.path.append(os.path.split(__file__)[0]) matplotlib.use('module://backend_sv4agg') except: pass import backend_sv4agg self.backend_sv4agg = backend_sv4agg dpath = matplotlib.rcParams['datapath'] tmp = os.path.join(dpath, 'images') if os.path.isdir(tmp): dpath = tmp winIcon = QIcon(os.path.join(dpath, 'matplotlib.png')) testAction = QAction(winIcon, QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin) testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction) return True
def main(): app = QApplication(sys.argv) widget = QWidget() QPixmap.grabWidget(widget, 100, 100, 200, 200) widget.show() app.exec_() e = Event() e.capture = False e.daemon = False e.start() while True: if e.is_press and e.is_release: if e.press_cnt == 1: if e.start_x > e.end_x: e.start_x, e.end_x = e.end_x, e.start_x if e.start_y > e.end_y: e.start_y, e.end_y = e.end_y, e.start_y width = e.end_x - e.start_x height = e.end_y - e.start_y f = tempfile.NamedTemporaryFile( prefix='screentshot_', suffix='.png') command = "import -window root -crop '%sx%s+%s+%s' " %( width, height, e.start_x, e.start_y) command += f.name EasyProcess(command).call() im = Image.open(f.name) im.show() break e.stop()
def __init__(self): Script.__init__(self, 'timeline') QWidget.__init__(self, None) self.type = 'timeline' self.nodeCount = 0 self.timesCount = 0 self.timeMap = {} self.m = 40 # Padding self.lineHeight = 4 # Pixel height of line self.metricOk = False self.colors = [['blue', Qt.blue], ['red', Qt.red], ['green', Qt.green], ['yellow', Qt.yellow], ['magenta', Qt.magenta], ['cyan', Qt.cyan]] self.stateinfo = 'Initialized' self.dateMin = long(0xffffffffffffffff) self.dateMax = long(0) self.baseDateMin = self.dateMin self.baseDateMax = self.dateMax self.selDateMin = None self.selDateMax = None self.maxOcc = 0 self.maxOccZoom = 0 self.xHop = 0 self.xRange = 0 self.dataListsCreated = False
def __init__(self): QDockWidget.__init__(self, "Help") self.setObjectName("HelpDock") widget = QWidget() widget.setStyleSheet("background-color: #ffffe0") layout = QVBoxLayout() widget.setLayout(layout) self.link_widget = QLabel() self.link_widget.setStyleSheet("font-weight: bold") self.link_widget.setMinimumHeight(20) self.help_widget = QLabel(HelpDock.default_help_string) self.help_widget.setWordWrap(True) self.help_widget.setTextFormat(Qt.RichText) self.validation_widget = QLabel("") self.validation_widget.setWordWrap(True) self.validation_widget.setScaledContents(True) self.validation_widget.setAlignment(Qt.AlignHCenter) self.validation_widget.setTextFormat(Qt.RichText) layout.addWidget(self.link_widget) layout.addWidget(self.help_widget) layout.addStretch(1) layout.addWidget(self.validation_widget) self.setWidget(widget) self.help_messages = {} MessageCenter().addHelpMessageListeners(self)
def __init__(self, parent=None, **kwargs): QWidget.__init__(self, parent, **kwargs) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.__tabs = [] self.__currentIndex = -1 self.__changeOnHover = False self.__iconSize = QSize(26, 26) self.__group = QButtonGroup(self, exclusive=True) self.__group.buttonPressed[QAbstractButton].connect( self.__onButtonPressed ) self.setMouseTracking(True) self.__sloppyButton = None self.__sloppyRegion = QRegion() self.__sloppyTimer = QTimer(self, singleShot=True) self.__sloppyTimer.timeout.connect(self.__onSloppyTimeout)
def __init__(self, IP, PORT, CameraID, parent=None): """ Initialization. """ QWidget.__init__(self, parent) self._image = QImage() self.setWindowTitle('Nao') self._imgWidth = 320 self._imgHeight = 240 self._cameraID = CameraID self.resize(self._imgWidth, self._imgHeight) # Proxy to ALVideoDevice. self._videoProxy = None # Our video module name. self._imgClient = "" # This will contain this alImage we get from Nao. self._alImage = None self._registerImageClient(IP, PORT) # Trigget 'timerEvent' every 100 ms. self.startTimer(100)
def build_form(self, parameters): """Build a form from impact functions parameter. .. note:: see http://tinyurl.com/pyqt-differences :param parameters: Parameters to be edited """ scroll_layout = QVBoxLayout() scroll_widget = QWidget() scroll_widget.setLayout(scroll_layout) scroll = QScrollArea() scroll.setWidgetResizable(True) scroll.setWidget(scroll_widget) self.configLayout.addWidget(scroll) for key, value in parameters.items(): if key == 'postprocessors': self.build_post_processor_form(value) elif key == 'minimum needs': self.build_minimum_needs_form(value) else: self.build_widget(scroll_layout, key, value) if scroll_layout.count() == 0: # Rizky: in case empty impact function, let's show some messages label = QLabel() message = tr('This impact function does not have any options to ' 'configure') label.setText(message) scroll_layout.addWidget(label) scroll_layout.addStretch()
def __init__(self, project, content, itemRelated, parent=None): QWidget.__init__(self, parent) self.__content = content.toMap() self.__project = project self.__favorite = QPushButton(self) self.__delete = QPushButton(self) self.__delete.setIcon(QIcon(resources.IMAGES['delProj'])) self.__name = QLineEdit(self) self.__itemRelated = itemRelated self.setMouseTracking(True) self.__name.setText(self.__content[QString("name")].toString()) if QString("description") in self.__content: description = self.__content[QString("description")].toString() else: description = self.tr("no description available") self.__name.setToolTip(self.tr(self.__project) + '\n\n' + description) self.__delete.setToolTip(self.tr("Click to delete from the list")) self.__favorite.setToolTip(self.tr("Click to dock on the list")) hbox = QHBoxLayout() self.setLayout(hbox) hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(self.__favorite) hbox.addWidget(self.__name) hbox.addWidget(self.__delete) self.__name.setCursor(QCursor(Qt.ArrowCursor)) self.__name.setReadOnly(True) self.connect(self.__favorite, SIGNAL("clicked(bool)"), self.__on_click_on_favorite) self.connect(self.__delete, SIGNAL("clicked(bool)"), self.__on_click_on_delete) #TODO: Change this click listen it doesn't work with ReadOnly = True self.connect(self.__name, SIGNAL("cursorPositionChanged(int, int)"), self.__on_click_on_name) self._set_favorite(self.__content[QString("isFavorite")].toBool())
def __init__(self, debug_controller, parent=None): QWidget.__init__(self, parent) self.gridLayout = QtGui.QGridLayout(self) self.gridLayout.setMargin(0) self.pyIoEdit = QtGui.QTextEdit(self) self.pyIoEdit.setReadOnly(True) self.gridLayout.addWidget(self.pyIoEdit, 0, 0, 1, 2) self.pyInputEdit = QtGui.QComboBox(self) self.pyInputEdit.setEditable(True) self.gridLayout.addWidget(self.pyInputEdit, 1, 0, 1, 1) self.pySendButton = QtGui.QPushButton(self) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pySendButton.sizePolicy().hasHeightForWidth()) self.pySendButton.setSizePolicy(sizePolicy) self.pySendButton.setText("Send") self.gridLayout.addWidget(self.pySendButton, 1, 1, 1, 1) QtCore.QMetaObject.connectSlotsByName(self) self.debugController = debug_controller self.pyInputEdit.lineEdit().returnPressed.connect(self.pySendButton.click) self.pySendButton.clicked.connect(self.executePythonCode)
def __init__(self, text_items, abstract, menu, parent=None): QWidget.__init__(self, parent) self.row_layout = QHBoxLayout(self) self.row_layout.setMargin(0) self.row_layout.setAlignment(Qt.AlignLeft) self.details_button = DetailsButton() self.row_layout.addWidget(self.details_button) for widget in (self.details_button, self): self.connect(widget, SIGNAL('clicked()'), self.updateView) for text in text_items: label = QLabel() label.setText("<h2>%s</h2>" % text) self.row_layout.addWidget(label) self.abstract = abstract if abstract is None: return self.row_layout.addWidget(abstract) self.row_layout.addStretch() self.edit_button = EditButton(menu) self.row_layout.addWidget(self.edit_button)
def generate_category_widget(symbolCategory, symbols, synchronizer): """ Generate the widget for a single symbolCategory. """ # layout for current tab currentWidget = QWidget() layout = SymbolSelectorGridLayout() currentWidget.setLayout(layout) # sort symbols in requested order rawList = [] for symbol in symbols: rawList.append((int(symbol["category_pos"]), symbol)) #rawList.sort(lambda x,y: cmp(x[0], y[0])) rawList.sort(key=(lambda x: x[0])) # add them to the tab widgetList = {} for (row, symbolEntry) in enumerate(rawList): symbol = symbolEntry[1] newItem = SymbolSelectorItem(symbol, synchronizer) newLabel = SymbolSelectorLabel(symbol) layout.append_row(newItem, newLabel) QObject.connect(newLabel, SIGNAL("label_clicked()"), newItem.click_me) widgetList[(symbol["name"], symbol["category"])] = newItem scrollArea = QScrollArea() scrollArea.setWidget(currentWidget) return (scrollArea, widgetList)
def __init__(self, color): QWidget.__init__(self) self.setMaximumSize(QSize(12, 12)) self.setMinimumSize(QSize(12, 12)) self.color = color
def __init__(self, app): QWidget.__init__(self, None) self.app = app self.boxModel = IgnoreBoxModel(app) self._setupUi() self.connect(self.browserView.selectionModel(), SIGNAL('selectionChanged(QItemSelection,QItemSelection)'), self.browserSelectionChanged)
def setModel(self, model): """ Set model used to store the data. This method adds an extra row at the end, which is used to keep the "Add..." button. """ super( DatasetDetailedInfoTableView, self ).setModel(model) widget = QWidget() layout = QHBoxLayout(widget) self._addButton = button = AddFileButton(widget, new=True) button.addFilesRequested.connect( partial(self.addFilesRequested.emit, -1)) button.addStackRequested.connect( partial(self.addStackRequested.emit, -1)) button.addRemoteVolumeRequested.connect( partial(self.addRemoteVolumeRequested.emit, -1)) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(button) layout.addStretch() widget.setLayout(layout) lastRow = self.model().rowCount()-1 modelIndex = self.model().index( lastRow, 0 ) self.setIndexWidget( modelIndex, widget ) # the "Add..." button spans last row self.setSpan(lastRow, 0, 1, model.columnCount())
def __init__(self, iface): QWidget.__init__(self) self.iface = iface self.setupUi(self) BaseBatchWidget.__init__(self, self.iface, "rgb2pct.py") self.outSelector.setType( self.outSelector.FILE ) # set the default QSpinBoxes and QProgressBar value self.colorsSpin.setValue(2) self.progressBar.setValue(0) self.progressBar.hide() self.outputFormat = Utils.fillRasterOutputFormat() self.setParamsStatus([ (self.inSelector, SIGNAL("filenameChanged()")), (self.outSelector, SIGNAL("filenameChanged()")), (self.colorsSpin, SIGNAL("valueChanged(int)"), self.colorsCheck), (self.bandSpin, SIGNAL("valueChanged(int)"), self.bandCheck, "-1") # hide this option ]) self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFile) self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit) self.connect( self.batchCheck, SIGNAL( "stateChanged( int )" ), self.switchToolMode )
def __init__(self, composer_wrapper, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self._composer_wrapper = composer_wrapper self._notif_bar = NotificationBar(self.vl_notification) self.cbo_chart_type.currentIndexChanged[int].connect(self._on_chart_type_changed) ''' Register chartname to the positional index of the corresponding editor ''' self._short_name_idx = {} #Add registered chart types self._load_chart_type_settings() #Load legend positions self._load_legend_positions() self.groupBox_2.setCollapsed(True) self.groupBox_2.collapsedStateChanged.connect(self._on_series_properties_collapsed) #Load fields if the data source has been specified ds_name = self._composer_wrapper.selectedDataSource() self.ref_table.load_data_source_fields(ds_name) #Load referenced table list self.ref_table.load_link_tables() #Connect signals self._composer_wrapper.dataSourceSelected.connect(self.ref_table.on_data_source_changed) self.ref_table.referenced_table_changed.connect(self.on_referenced_table_changed)
def setupUi(self): self.setLayout(QVBoxLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.layout().setSpacing(0) self.__mainLayout = QVBoxLayout() self.__mainLayout.setContentsMargins(0, 40, 0, 40) self.__mainLayout.setSpacing(65) self.layout().addLayout(self.__mainLayout) self.setStyleSheet(WELCOME_WIDGET_BUTTON_STYLE) bottom_bar = QWidget(objectName="bottom-bar") bottom_bar_layout = QHBoxLayout() bottom_bar_layout.setContentsMargins(20, 10, 20, 10) bottom_bar.setLayout(bottom_bar_layout) bottom_bar.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum) check = QCheckBox(self.tr("Show at startup"), bottom_bar) check.setChecked(False) self.__showAtStartupCheck = check bottom_bar_layout.addWidget(check, alignment=Qt.AlignVCenter | \ Qt.AlignLeft) self.layout().addWidget(bottom_bar, alignment=Qt.AlignBottom, stretch=1) self.setSizeGripEnabled(False) self.setFixedSize(620, 390)
def __addSectionSpacer( self ): " Adds a fixed height spacer to the VBox layout " spacer = QWidget() spacer.setFixedHeight( 10 ) self.__vLayout.addWidget( spacer ) self.__widgets.append( spacer ) return
def __init__(self, parent): QWidget.__init__(self, parent) self.parent = parent self.objets = parent.objets self.sizer = QVBoxLayout() self.infos = infos = QVBoxLayout() if len(self.objets) == 1: self.objet = self.objets[0] else: self.objet = None # cela n'a pas vraiment de sens d'afficher une longueur pour 3 segments differents par exemple... self.textes = [] proprietes = ("aire", "centre", "coordonnees", "rayon", "longueur", "perimetre", "norme", "sens") for propriete in proprietes: try: self.ajouter(infos, propriete) except: debug(u"Erreur lors de la lecture de la propriété '%s' de l'objet %s." %(propriete, self.objet.nom)) print_error() self.ajouter(infos, "equation_formatee", u"Equation cartésienne") if self.textes: infos_box = QGroupBox(u"Informations") infos_box.setLayout(infos) self.sizer.addWidget(infos_box) actualiser = QPushButton(u"Actualiser") actualiser.clicked.connect(self.EvtActualiser) self.sizer.addWidget(actualiser) else: self.sizer.addWidget(QLabel(str(len(self.objets)) + u" objets sélectionnés.")) self.setLayout(self.sizer)
def __init__(self): QWidget.__init__(self) layout = QHBoxLayout() layout.addSpacing(10) workflow_model = WorkflowsModel() # workflow_model.observable().attach(WorkflowsModel.CURRENT_CHOICE_CHANGED_EVENT, self.showWorkflow) workflow_combo = ComboChoice(workflow_model, "Select Workflow", "run/workflow") layout.addWidget(QLabel(workflow_combo.getLabel()), 0, Qt.AlignVCenter) layout.addWidget(workflow_combo, 0, Qt.AlignVCenter) # simulation_mode_layout.addStretch() layout.addSpacing(20) self.run_button = QToolButton() self.run_button.setIconSize(QSize(32, 32)) self.run_button.setText("Start Workflow") self.run_button.setIcon(util.resourceIcon("ide/gear_in_play")) self.run_button.clicked.connect(self.startWorkflow) self.run_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) layout.addWidget(self.run_button) layout.addStretch(1) self.setLayout(layout) self.__running_workflow_dialog = None self.workflowSucceeded.connect(self.workflowFinished) self.workflowFailed.connect(self.workflowFinishedWithFail)
def addSpace(self, size=5): """Creates a widget that can be used as spacing on a panel.""" space = QWidget() space.setMinimumSize(QSize(size, size)) self.__startNewRow() self.__layout.addWidget(space, self.__row, 1, 1, 5) self.__rowFinished()
def __init__(self, parent = None): QWidget.__init__(self, parent) self.lmbDown = False self.setMouseTracking(True) self.setAutoFillBackground(True) self._layerPainter = LayerPainter() self._layer = None
def __init__(self, direction, parent=None): """Create a new instance.""" QWidget.__init__(self, parent) if not direction in (QArrow.UP, QArrow.DOWN, QArrow.LEFT, QArrow.RIGHT): raise ValueError('Wrong arrow direction.') self._direction = direction
def __init__(self, parent): QWidget.__init__(self, parent) self.parent = parent self.objets = parent.objets self.panel = self.parent.parent.panel self.canvas = self.parent.parent.canvas self.islabel = self.parent.parent.islabel self.sizer = QVBoxLayout() if len(self.objets) is 1: self.objet = self.objets[0] style = QVBoxLayout() style_box = QGroupBox(u"Style de l'objet") style_box.setLayout(style) style.addWidget(QLabel(u"Attention, ne modifiez ce contenu que si vous savez ce que vous faites.")) self.avance = QTextEdit() self.avance.setMinimumSize(350, 200) self.actualiser() style.addWidget(self.avance) self.sizer.addWidget(style_box) ok = QPushButton('OK') appliquer = QPushButton(u"Appliquer") actualiser = QPushButton(u"Actualiser") ok.clicked.connect(self.EvtOk) appliquer.clicked.connect(self.EvtAppliquer) actualiser.clicked.connect(self.actualiser) boutons = QHBoxLayout() boutons.addWidget(ok) boutons.addWidget(appliquer) boutons.addWidget(actualiser) self.sizer.addLayout(boutons) self.setLayout(self.sizer)
def __init__(self, parent = None): QWidget.__init__(self, parent) self.setStyleSheet(SHARED) self.layout = QVBoxLayout(self) disk1 = Block(self, 'Western Digital ATA', 2220)#, layout = VERTICAL) disk1.addPartition(Partition(disk1, 'sda1', EXT, 800)) disk1.addPartition(Partition(disk1, 'sda2', MS, 400)) disk1.addPartition(Partition(disk1, 'sda3', UK, 620)) disk1.addPartition(Partition(disk1, 'free', FREE)) self.layout.addWidget(disk1) disk2 = Block(self, 'Seagate Falan Filan', 5330)#, layout = VERTICAL) disk2.addPartition(Partition(disk2, 'sdb1', UK, 120)) disk2.addPartition(Partition(disk2, 'sdb2', EXT, 530)) disk2.addPartition(Partition(disk2, 'sdb3', EXT, 2830)) disk2.addPartition(Partition(disk2, 'free', FREE)) self.layout.addWidget(disk2) disk3 = Block(self, 'Super USB Disk', 4330)#, layout = VERTICAL) disk3.addPartition(Partition(disk3, 'free', FREE, 2220)) disk3.addPartition(Partition(disk3, 'sdc1', EXT, 1000)) disk3.addPartition(Partition(disk3, 'sdc2', MS, 620)) disk3.addPartition(Partition(disk3, 'free', FREE)) self.layout.addWidget(disk3) disk1.connectToBlock(disk2) disk1.connectToBlock(disk3) disk2.connectToBlock(disk3)
def __init__( self, parent = None ): QWidget.__init__( self, parent ) self.__reportUUID = "" self.__reportFileName = "" self.__reportOption = -1 self.__reportShown = False self.__report = None self.__widgets = [] # Prepare members for reuse if GlobalData().pylintAvailable: self.__noneLabel = QLabel( "\nNo results available" ) else: self.__noneLabel = QLabel( "\nPylint is not available" ) self.__noneLabel.setAutoFillBackground( True ) noneLabelPalette = self.__noneLabel.palette() noneLabelPalette.setColor( QPalette.Background, GlobalData().skin.nolexerPaper ) self.__noneLabel.setPalette( noneLabelPalette ) self.__noneLabel.setFrameShape( QFrame.StyledPanel ) self.__noneLabel.setAlignment( Qt.AlignHCenter ) self.__headerFont = self.__noneLabel.font() self.__headerFont.setPointSize( self.__headerFont.pointSize() + 4 ) self.__noneLabel.setFont( self.__headerFont ) self.__createLayout( parent ) self.__updateButtonsStatus() self.resizeEvent() return
def resizeEvent(self, event): QWidget.resizeEvent(self, event) self.recalculate_size()
class __StatusBar(QStatusBar): def __init__(self, parent=None): QStatusBar.__init__(self, parent) self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget(self) vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget(self) vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget(self) vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) self._shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._replaceWidget._btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self._replaceWidget._btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self._shortEsc, SIGNAL("activated()"), self.hide_status) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) def explore_code(self): self._codeLocator.explore_code() def explore_file_code(self, path): self._codeLocator.explore_file_code(path) def show(self): self.clearMessage() QStatusBar.show(self) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll() def show_replace(self): self.clearMessage() self.show() editor = main_container.MainContainer().get_actual_editor() if editor: if editor.textCursor().hasSelection(): word = editor.textCursor().selectedText() self._searchWidget._line.setText(word) self._replaceWidget.setVisible(True) def show_with_word(self): self.clearMessage() editor = main_container.MainContainer().get_actual_editor() if editor: word = editor._text_under_cursor() self._searchWidget._line.setText(word) editor = main_container.MainContainer().get_actual_editor() editor.moveCursor(QTextCursor.WordLeft) self._searchWidget.find_matches(editor) self.show() def show_locator(self): self.clearMessage() self._searchWidget.setVisible(False) self.show() self._codeLocator.setVisible(True) self._codeLocator._completer.setFocus() self._codeLocator.show_suggestions() def show_file_opener(self): self.clearMessage() self._searchWidget.setVisible(False) self._fileSystemOpener.setVisible(True) self.show() self._fileSystemOpener.pathLine.setFocus() def hide_status(self): self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked) self._searchWidget._checkWholeWord.setCheckState(Qt.Unchecked) self.hide() self._searchWidget.setVisible(True) self._replaceWidget.setVisible(False) self._codeLocator.setVisible(False) self._fileSystemOpener.setVisible(False) widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus() def replace(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(unicode(self._searchWidget._line.text()), unicode(self._replaceWidget._lineReplace.text()), flags) self.find() def replace_all(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(unicode(self._searchWidget._line.text()), unicode(self._replaceWidget._lineReplace.text()), flags, True) def find(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags) def find_next(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags, True) def find_previous(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 1 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags, True) def showMessage(self, message, timeout): self._widgetStatus.hide() self._replaceWidget.setVisible(False) self.show() QStatusBar.showMessage(self, message, timeout) def message_end(self, message): if message == '': self.hide() QStatusBar.clearMessage(self) self._widgetStatus.show() widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus()
root = Tkinter.Tk() root.withdraw() dirname = tkFileDialog.askdirectory( parent=root, initialdir="/Desktop", title= 'You are downloading a file, please select a directory to place the file. Close the window to cancel' ) if dirname.strip() != '': dirname = dirname.replace('/', '\\') f = open(dirname + '\\' + filename, 'wb') f.write(str(self.reply.readAll())) f.close() else: pass if __name__ == "__main__": app = QApplication(sys.argv) grid = QGridLayout() browser = QWebView() url_input = UrlInput(browser) grid.addWidget(url_input, 1, 0) grid.addWidget(browser, 2, 0) main_frame = QWidget() main_frame.setLayout(grid) main_frame.show() sys.exit(app.exec_())
def __init__(self, parent, apply_callback=None): QWidget.__init__(self, parent) self.apply_callback = apply_callback self.is_modified = False
def resizeEvent(self, event): QWidget.resizeEvent(self, event) return
def __createLayout(self): " Creates the toolbar and layout " # Buttons self.__printButton = QAction(PixmapCache().getIcon('printer.png'), 'Print', self) self.__printButton.triggered.connect(self.__onPrint) self.__printButton.setEnabled(False) self.__printButton.setVisible(False) self.__printPreviewButton = QAction( PixmapCache().getIcon('printpreview.png'), 'Print preview', self) self.__printPreviewButton.triggered.connect(self.__onPrintPreview) self.__printPreviewButton.setEnabled(False) self.__printPreviewButton.setVisible(False) # self.__sendUpButton = QAction( PixmapCache().getIcon('sendioup.png'), # 'Send to Main Editing Area', self ) # self.__sendUpButton.triggered.connect( self.__sendUp ) self.__filterMenu = QMenu(self) self.__filterMenu.aboutToShow.connect(self.__filterAboutToShow) self.__filterGroup = QActionGroup(self) self.__filterShowAllAct = self.__filterMenu.addAction("Show all") self.__filterShowAllAct.setCheckable(True) self.__filterShowAllAct.setActionGroup(self.__filterGroup) self.__filterShowAllAct.triggered.connect(self.__onFilterShowAll) self.__filterShowStdoutAct = self.__filterMenu.addAction( "Show stdin and stdout") self.__filterShowStdoutAct.setCheckable(True) self.__filterShowStdoutAct.setActionGroup(self.__filterGroup) self.__filterShowStdoutAct.triggered.connect(self.__onFilterShowStdout) self.__filterShowStderrAct = self.__filterMenu.addAction( "Show stdin and stderr") self.__filterShowStderrAct.setCheckable(True) self.__filterShowStderrAct.setActionGroup(self.__filterGroup) self.__filterShowStderrAct.triggered.connect(self.__onFilterShowStderr) self.__filterButton = QToolButton(self) self.__filterButton.setIcon(PixmapCache().getIcon('iofilter.png')) self.__filterButton.setToolTip('Filtering settings') self.__filterButton.setPopupMode(QToolButton.InstantPopup) self.__filterButton.setMenu(self.__filterMenu) self.__filterButton.setFocusPolicy(Qt.NoFocus) self.__settingsMenu = QMenu(self) self.__settingsMenu.aboutToShow.connect(self.__settingsAboutToShow) self.__wrapLongLinesAct = self.__settingsMenu.addAction( "Wrap long lines") self.__wrapLongLinesAct.setCheckable(True) self.__wrapLongLinesAct.triggered.connect(self.__onWrapLongLines) self.__showEOLAct = self.__settingsMenu.addAction("Show EOL") self.__showEOLAct.setCheckable(True) self.__showEOLAct.triggered.connect(self.__onShowEOL) self.__showWhitespacesAct = self.__settingsMenu.addAction( "Show whitespaces") self.__showWhitespacesAct.setCheckable(True) self.__showWhitespacesAct.triggered.connect(self.__onShowWhitespaces) self.__autoscrollAct = self.__settingsMenu.addAction("Autoscroll") self.__autoscrollAct.setCheckable(True) self.__autoscrollAct.triggered.connect(self.__onAutoscroll) self.__showMarginAct = self.__settingsMenu.addAction( "Show timestamp margin") self.__showMarginAct.setCheckable(True) self.__showMarginAct.triggered.connect(self.__onShowMargin) self.__settingsButton = QToolButton(self) self.__settingsButton.setIcon(PixmapCache().getIcon('iosettings.png')) self.__settingsButton.setToolTip('View settings') self.__settingsButton.setPopupMode(QToolButton.InstantPopup) self.__settingsButton.setMenu(self.__settingsMenu) self.__settingsButton.setFocusPolicy(Qt.NoFocus) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.__clearButton = QAction(PixmapCache().getIcon('trash.png'), 'Clear', self) self.__clearButton.triggered.connect(self.clear) # The toolbar toolbar = QToolBar(self) toolbar.setOrientation(Qt.Vertical) toolbar.setMovable(False) toolbar.setAllowedAreas(Qt.RightToolBarArea) toolbar.setIconSize(QSize(16, 16)) toolbar.setFixedWidth(28) toolbar.setContentsMargins(0, 0, 0, 0) # toolbar.addAction( self.__sendUpButton ) toolbar.addAction(self.__printPreviewButton) toolbar.addAction(self.__printButton) toolbar.addWidget(self.__filterButton) toolbar.addWidget(self.__settingsButton) toolbar.addWidget(spacer) toolbar.addAction(self.__clearButton) hLayout = QHBoxLayout() hLayout.setContentsMargins(0, 0, 0, 0) hLayout.setSpacing(0) hLayout.addWidget(toolbar) hLayout.addWidget(self.__viewer) self.setLayout(hLayout) return
def __init__(self, parent=None, autoupdate=Event()): QWidget.__init__(self, parent) # self.app = QApplication(sys.argv) # window = QMainWindow() self.my_gauge = Ui_MainWindow() self.my_gauge.setupUi(self) self.maxButton_NameTextLenght = 15 # Max charcters # self.my_gauge.name_list.setFont() self.my_gauge.widget.enable_barGraph = True self.my_gauge.widget.value_needle_snapzone = 1 self.my_gauge.widget.set_scale_polygon_colors([[.0, Qt.green], [.1, Qt.green], [.25, Qt.yellow], [.55, Qt.blue], [.95, Qt.darkBlue]]) # self.my_gauge.ActualSlider.setMaximum(self.my_gauge.widget.value_max) # self.my_gauge.ActualSlider.setMinimum(self.my_gauge.widget.value_min) # self.my_gauge.AussenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_outer_radius_factor * 1000) # self.my_gauge.InnenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_inner_radius_factor * 1000) # self.my_gauge.GaugeStartSlider.setValue(self.my_gauge.widget.scale_angle_start_value) # self.my_gauge.GaugeSizeSlider.setValue(self.my_gauge.widget.scale_angle_size) self.my_gauge.pushButton.clicked.connect(self.start_timer) self.my_gauge.pushButton_openfile.clicked.connect(self.openfile_read_list) self.my_gauge.pushButton_clear.clicked.connect(self.clear_name_list_widget) self.my_gauge.name_list.itemSelectionChanged.connect(self.item_selection_changed) self.my_gauge.checkBox_toggle_info.stateChanged.connect(self.toggle_info) # self.my_gauge.widge self.my_gauge.widget.set_enable_ScaleText(False) self.autoupdate = autoupdate self.starten = Event() self.stoppen = Event() self.new_data = Queue() self.reset = Event() self.my_queue = Queue() button_x_size = 30 button_y_size = 30 x_pos = 20 y_pos = 0 self.button_ring =(QPushButton(str("sec"), self)) self.button_ring.setGeometry(x_pos, y_pos, button_x_size, button_y_size) self.button_ring.clicked.connect(self.set_timer_seconds) self.button_ring.move(x_pos - button_x_size / 2, y_pos) # + button_y_size / 2) self.button_ring.show() self.button_panel =(QPushButton(str(">"), self)) self.button_panel.setGeometry(x_pos+button_x_size, y_pos, button_x_size, button_y_size) self.button_panel.clicked.connect(self.toggle_panel) self.button_panel.move((x_pos - button_x_size / 2) + button_x_size, y_pos) # + button_y_size / 2) self.button_panel.show() text_x_size = 500 text_y_size = 75 self.name_highlight = QLabel(self) self.name_highlight.setGeometry(x_pos+(button_x_size*2), 0, text_x_size, text_y_size) self.name_highlight.move(x_pos + button_x_size*2 - button_x_size/2, -20) # self.name_highlight.setGeometry(30, 30, text_x_size, text_y_size) # self.name_highlight.move(70, -10) self.name_highlight.setText("") myfont = QFont("Segoe UI", 30) myfont.setBold(True) self.name_highlight.setFont(myfont) self.name_highlight.show() self.panel_show = True # self.toggle_button_label_info = False self.toggle_button_label_info = self.my_gauge.checkBox_toggle_info.checkState() # self.toggle_info() self.toggle_show_name_label() self.my_gauge.checkBox_show_name_label.stateChanged.connect(self.toggle_show_name_label) # Disable standard AnalogGaugeWidget float value, to replace with human readable time values self.my_gauge.widget.set_enable_value_text(False) self.my_gauge.widget.enable_user_defined_value_text = True self.running = sut(self.starten, self.stoppen, self.reset, self.my_queue, self.new_data) self.running.start() self.set_time(30) time.sleep(0.1) # self.starten.set() self.state_dict = {"init": "start", "reset": "start", "start": "stop", "stop": "reset"} self.actual_state = "init" print(self.actual_state) # add banner image banner_name = "banner.png" banner_path = os.path.dirname(__file__) + os.path.sep + banner_name self.pixmap = QPixmap(banner_path) # self.pixmap = self.pixmap.scaledToWidth(300) self.my_gauge.banner.setPixmap(self.pixmap) self.my_gauge.banner.setScaledContents(True) self.my_gauge.widget.initial_value_fontsize = 50 QTimer.singleShot(10, self.check_new_data) self.update() self.toggle_info()
def __init__(self, parameter, parent=None): """Constructor :param parameter: A DefaultSelectParameter object. :type parameter: DefaultSelectParameter """ super(DefaultSelectParameterWidget, self).__init__(parameter, parent) self.default_layout = QHBoxLayout() self.radio_button_layout = QHBoxLayout() self.radio_button_widget = QWidget() self.default_label = QLabel(tr('Default')) # Create radio button group self.default_input_button_group = QButtonGroup() # Define string enabler for radio button self.radio_button_enabler = self.input.itemData(0, Qt.UserRole) for i in range(len(self._parameter.default_labels)): if '%s' in self._parameter.default_labels[i]: label = ( self._parameter.default_labels[i] % self._parameter.default_values[i]) else: label = self._parameter.default_labels[i] radio_button = QRadioButton(label) self.radio_button_layout.addWidget(radio_button) self.default_input_button_group.addButton(radio_button, i) if self._parameter.default_value == \ self._parameter.default_values[i]: radio_button.setChecked(True) # Create double spin box for custom value self.custom_value = QDoubleSpinBox() if self._parameter.default_values[-1]: self.custom_value.setValue(self._parameter.default_values[-1]) has_min = False if self._parameter.minimum is not None: has_min = True self.custom_value.setMinimum(self._parameter.minimum) has_max = False if self._parameter.maximum is not None: has_max = True self.custom_value.setMaximum(self._parameter.maximum) if has_min and has_max: step = (self._parameter.maximum - self._parameter.minimum) / 100.0 self.custom_value.setSingleStep(step) self.radio_button_layout.addWidget(self.custom_value) self.toggle_custom_value() # Reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QGridLayout() self.input_layout.setSpacing(0) self.input_layout.addWidget(self.label, 0, 0) self.input_layout.addLayout(self.inner_input_layout, 0, 1) self.input_layout.addWidget(self.default_label, 1, 0) self.input_layout.addLayout(self.radio_button_layout, 1, 1) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) # check every added combobox, it could have been toggled by # the existing keyword self.toggle_input() # Connect # noinspection PyUnresolvedReferences self.input.currentIndexChanged.connect(self.toggle_input) self.default_input_button_group.buttonClicked.connect( self.toggle_custom_value)
def __createLayout(self, parent): " Creates the toolbar and layout " # Buttons self.printButton = QAction(PixmapCache().getIcon('printer.png'), 'Print', self) #printButton.setShortcut( 'Ctrl+' ) self.printButton.triggered.connect(self.__onPrint) self.printButton.setVisible(False) self.printPreviewButton = QAction( PixmapCache().getIcon('printpreview.png'), 'Print preview', self) #printPreviewButton.setShortcut( 'Ctrl+' ) self.printPreviewButton.triggered.connect(self.__onPrintPreview) self.printPreviewButton.setVisible(False) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.clearButton = QAction(PixmapCache().getIcon('trash.png'), 'Clear', self) self.clearButton.triggered.connect(self.__clear) # The toolbar self.toolbar = QToolBar(self) self.toolbar.setOrientation(Qt.Vertical) self.toolbar.setMovable(False) self.toolbar.setAllowedAreas(Qt.RightToolBarArea) self.toolbar.setIconSize(QSize(16, 16)) self.toolbar.setFixedWidth(28) self.toolbar.setContentsMargins(0, 0, 0, 0) self.toolbar.addAction(self.printPreviewButton) self.toolbar.addAction(self.printButton) self.toolbar.addWidget(spacer) self.toolbar.addAction(self.clearButton) self.__vLayout = QVBoxLayout() self.__vLayout.setContentsMargins(5, 5, 5, 5) self.__vLayout.setSpacing(0) self.__vLayout.setSizeConstraint(QLayout.SetFixedSize) self.__bodyFrame = QFrame(self) # self.__bodyFrame.setFrameShape( QFrame.StyledPanel ) self.__bodyFrame.setFrameShape(QFrame.NoFrame) # self.__bodyFrame.setSizePolicy( QSizePolicy.Maximum, # QSizePolicy.Expanding ) self.__bodyFrame.setLayout(self.__vLayout) self.bodyWidget = QScrollArea(self) self.bodyWidget.setFocusPolicy(Qt.NoFocus) self.bodyWidget.setWidget(self.__bodyFrame) self.bodyWidget.hide() self.__hLayout = QHBoxLayout() self.__hLayout.setContentsMargins(0, 0, 0, 0) self.__hLayout.setSpacing(0) self.__hLayout.addWidget(self.toolbar) self.__hLayout.addWidget(self.__noneLabel) self.__hLayout.addWidget(self.bodyWidget) self.setLayout(self.__hLayout) return
def __init__(self, iface, db, parent=None): QWidget.__init__(self, parent) self.iface = iface self.db = db self.filter = "" self.allowMultiColumnPk = isinstance( db, PGDatabase ) # at the moment only PostgreSQL allows a primary key to span multiple columns, spatialite doesn't self.aliasSubQuery = isinstance( db, PGDatabase) # only PostgreSQL requires subqueries to be aliases self.setupUi(self) self.setWindowTitle( u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString())) self.defaultLayerName = 'QueryLayer' if self.allowMultiColumnPk: self.uniqueColumnCheck.setText( self.trUtf8("Column(s) with unique values")) else: self.uniqueColumnCheck.setText( self.trUtf8("Column with unique values")) self.editSql.setFocus() self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.initCompleter() # allow copying results copyAction = QAction("copy", self) self.viewResult.addAction(copyAction) copyAction.setShortcuts(QKeySequence.Copy) copyAction.triggered.connect(self.copySelectedResults) self.btnExecute.clicked.connect(self.executeSql) self.btnSetFilter.clicked.connect(self.setFilter) self.btnClear.clicked.connect(self.clearSql) self.presetStore.clicked.connect(self.storePreset) self.presetDelete.clicked.connect(self.deletePreset) self.presetCombo.activated[str].connect(self.loadPreset) self.presetCombo.activated[str].connect(self.presetName.setText) self.updatePresetsCombobox() self.geomCombo.setEditable(True) self.geomCombo.lineEdit().setReadOnly(True) self.uniqueCombo.setEditable(True) self.uniqueCombo.lineEdit().setReadOnly(True) self.uniqueModel = QStandardItemModel(self.uniqueCombo) self.uniqueCombo.setModel(self.uniqueModel) if self.allowMultiColumnPk: self.uniqueCombo.setItemDelegate(QStyledItemDelegate()) self.uniqueModel.itemChanged.connect( self.uniqueChanged) # react to the (un)checking of an item self.uniqueCombo.lineEdit().textChanged.connect( self.uniqueTextChanged ) # there are other events that change the displayed text and some of them can not be caught directly # hide the load query as layer if feature is not supported self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport() self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable) if self._loadAsLayerAvailable: self.layerTypeWidget.hide() # show if load as raster is supported self.loadLayerBtn.clicked.connect(self.loadSqlLayer) self.getColumnsBtn.clicked.connect(self.fillColumnCombos) self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled) self.loadAsLayerToggled(False) self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport( ) self.btnCreateView.setVisible(self._createViewAvailable) if self._createViewAvailable: self.btnCreateView.clicked.connect(self.createView) self.queryBuilderFirst = True self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif")) self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder) self.presetName.textChanged.connect(self.nameChanged)
def hideEvent(self, event): self.set_program_callbacks_enabled(False) QWidget.hideEvent(self, event)
def __init__(self,parent=None): QWidget.__init__(self,parent) print os.getcwd() self.ui=uic.loadUi("DelayStage.ui",self) self.delaystage=DelayStage(self)
class GertMainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.tools = {} self.resize(300, 700) self.setWindowTitle('ERT') self.__main_widget = None self.central_widget = QWidget() self.central_layout = QVBoxLayout() self.central_widget.setLayout(self.central_layout) self.setCentralWidget(self.central_widget) self.toolbar = self.addToolBar("Tools") self.toolbar.setObjectName("Toolbar") self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.setCorner(Qt.TopLeftCorner, Qt.LeftDockWidgetArea) self.setCorner(Qt.BottomLeftCorner, Qt.BottomDockWidgetArea) self.setCorner(Qt.TopRightCorner, Qt.RightDockWidgetArea) self.setCorner(Qt.BottomRightCorner, Qt.BottomDockWidgetArea) self.__view_menu = None self.__help_menu = None self.__createMenu() self.__fetchSettings() def addDock(self, name, widget, area=Qt.RightDockWidgetArea, allowed_areas=Qt.AllDockWidgetAreas): dock_widget = QDockWidget(name) dock_widget.setObjectName("%sDock" % name) dock_widget.setWidget(widget) dock_widget.setAllowedAreas(allowed_areas) self.addDockWidget(area, dock_widget) self.__view_menu.addAction(dock_widget.toggleViewAction()) return dock_widget def addTool(self, tool): tool.setParent(self) self.tools[tool.getName()] = tool self.toolbar.addAction(tool.getAction()) if tool.isPopupMenu(): tool_button = self.toolbar.widgetForAction(tool.getAction()) tool_button.setPopupMode(QToolButton.InstantPopup) def __createMenu(self): file_menu = self.menuBar().addMenu("&File") file_menu.addAction("Close", self.__quit) self.__view_menu = self.menuBar().addMenu("&View") self.__help_menu = self.menuBar().addMenu("&Help") """:type: QMenu""" """ @rtype: list of QAction """ show_about = self.__help_menu.addAction("About") show_about.setMenuRole(QAction.ApplicationSpecificRole) show_about.triggered.connect(self.__showAboutMessage) def __quit(self): self.__saveSettings() qApp.quit() def __saveSettings(self): settings = QSettings("Statoil", "Ert-Gui") settings.setValue("geometry", self.saveGeometry()) settings.setValue("windowState", self.saveState()) def closeEvent(self, event): #Use QT settings saving mechanism #settings stored in ~/.config/Statoil/ErtGui.conf self.__saveSettings() QMainWindow.closeEvent(self, event) def __fetchSettings(self): settings = QSettings("Statoil", "Ert-Gui") if sys.version_info[0] == 2: self.restoreGeometry(settings.value("geometry").toByteArray()) self.restoreState(settings.value("windowState").toByteArray()) else: self.restoreGeometry(settings.value("geometry")) self.restoreState(settings.value("windowState")) def setWidget(self, widget): self.__main_widget = widget actions = widget.getActions() for action in actions: self.__view_menu.addAction(action) self.central_layout.addWidget(widget) def __showAboutMessage(self): diag = AboutDialog(self) diag.show() pass
def __init__(self, session, script_manager, image_version, executable_versions, program): QWidget.__init__(self) self.setupUi(self) self.session = session self.script_manager = script_manager self.image_version = image_version self.executable_versions = executable_versions self.program = program self.root_directory = self.program.root_directory self.last_upload_files_wizard_directory = get_home_path() self.program.scheduler_state_changed_callback = self.scheduler_state_changed self.program.lite_scheduler_state_changed_callback = self.lite_scheduler_state_changed self.program.process_spawned_callback = self.process_spawned self.program.lite_process_spawned_callback = self.lite_process_spawned if self.program.last_spawned_process != None: self.program.last_spawned_process.state_changed_callback = self.process_state_changed if self.program.last_spawned_lite_process != None: self.program.last_spawned_lite_process.state_changed_callback = self.lite_process_state_changed self.first_show_event = True self.tab_is_alive = True self.program_refresh_in_progress = False self.edit_general_wizard = None self.edit_language_wizard = None self.edit_arguments_wizard = None self.edit_stdio_wizard = None self.edit_schedule_wizard = None self.upload_files_wizard = None self.download_wizard = None self.button_refresh.clicked.connect(self.refresh_info) self.button_start_program.clicked.connect(self.start_program) self.button_exit_process.clicked.connect(self.exit_process) self.button_kill_process.clicked.connect(self.kill_process) self.button_continue_schedule.clicked.connect(self.continue_schedule) self.button_send_stdin_pipe_input.clicked.connect( self.send_stdin_pipe_input) self.check_show_environment.stateChanged.connect(self.update_ui_state) self.button_edit_general.clicked.connect(self.show_edit_general_wizard) self.button_edit_language.clicked.connect( self.show_edit_language_wizard) self.button_edit_arguments.clicked.connect( self.show_edit_arguments_wizard) self.button_edit_stdio.clicked.connect(self.show_edit_stdio_wizard) self.button_edit_schedule.clicked.connect( self.show_edit_schedule_wizard) # create language info widget language_api_name = self.program.cast_custom_option_value( 'language', unicode, '<unknown>') try: language = Constants.get_language(language_api_name) except: language = None if language != None: language_info_classes = { Constants.LANGUAGE_C: ProgramInfoC, Constants.LANGUAGE_CSHARP: ProgramInfoCSharp, Constants.LANGUAGE_DELPHI: ProgramInfoDelphi, Constants.LANGUAGE_JAVA: ProgramInfoJava, Constants.LANGUAGE_JAVASCRIPT: ProgramInfoJavaScript, Constants.LANGUAGE_OCTAVE: ProgramInfoOctave, Constants.LANGUAGE_PERL: ProgramInfoPerl, Constants.LANGUAGE_PHP: ProgramInfoPHP, Constants.LANGUAGE_PYTHON: ProgramInfoPython, Constants.LANGUAGE_RUBY: ProgramInfoRuby, Constants.LANGUAGE_SHELL: ProgramInfoShell, Constants.LANGUAGE_VBNET: ProgramInfoVBNET } if language_info_classes[language] != None: context = ProgramInfoContext(self.session, self.script_manager, self.executable_versions, self.program) self.widget_language = language_info_classes[language](context) self.layout_language.addWidget(self.widget_language) else: self.widget_language = None else: self.widget_language = None self.current_language_action = None self.button_language_action.setVisible(False) def is_alive(): return self.tab_is_alive # create logs info widget context = ProgramInfoContext(self.session, self.script_manager, self.executable_versions, self.program) self.widget_logs = ProgramInfoLogs(context, self.update_ui_state, self.set_widget_enabled, is_alive, self.show_download_wizard, self.set_program_callbacks_enabled) self.layout_logs.addWidget(self.widget_logs) # create files info widget context = ProgramInfoContext(self.session, self.script_manager, self.executable_versions, self.program) self.widget_files = ProgramInfoFiles(context, self.update_ui_state, self.set_widget_enabled, is_alive, self.show_upload_files_wizard, self.show_download_wizard) self.layout_files.addWidget(self.widget_files) self.update_ui_state()
def main(): """Main function""" application = QApplication([]) name_parameter = StringParameter('UUID-1') name_parameter.name = 'Resource name' name_parameter.help_text = ( 'Name of the resource that will be provided as part of minimum needs.' 'e.g. Tea, Water etc.') name_parameter.description = ( 'A <b>resource</b> is something that you provide to displaced persons ' 'in the event of a disaster. The resource will be made available ' 'at IDP camps and may need to be stockpiled by contingency planners ' 'in their preparations for a disaster.') name_parameter.is_required = True name_parameter.value = '' description_parameter = StringParameter('UUID-1') description_parameter.name = 'Resource description' description_parameter.help_text = ( 'Description of the resource that will be provided as part of minimum ' 'needs. e.g. Tea, Water etc.') description_parameter.description = ( 'Description of the resource that will be provided as part of minimum ' 'needs. e.g. Tea, Water etc.') description_parameter.is_required = True description_parameter.value = '' unit_parameter = StringParameter('UUID-2') unit_parameter.name = 'Units' unit_parameter.help_text = ('Unit for the resources. e.g. litres, kg etc.') unit_parameter.description = ( 'A <b>unit</b> the basic measurement unit used for computing the ' 'allowance per individual. For example when planning water rations ' 'the units would be litres.') unit_parameter.is_required = True unit_parameter.value = '' minimum_parameter = FloatParameter('UUID-3') minimum_parameter.name = 'Minimum allowed' minimum_parameter.is_required = True minimum_parameter.precision = 3 minimum_parameter.minimum_allowed_value = -99999.0 minimum_parameter.maximum_allowed_value = 99999.0 minimum_parameter.help_text = 'The minimum allowable quantity per person. ' minimum_parameter.description = ( 'The <b>minimum</b> is the minimum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be less than 0.5l.') minimum_parameter.value = 1.0 maximum_parameter = FloatParameter('UUID-3') maximum_parameter.name = 'Minimum allowed' maximum_parameter.is_required = True maximum_parameter.precision = 3 maximum_parameter.minimum_allowed_value = -99999.0 maximum_parameter.maximum_allowed_value = 99999.0 maximum_parameter.help_text = 'The maximum allowable quantity per person. ' maximum_parameter.description = ( 'The <b>maximum</b> is the maximum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be more than 50l.') maximum_parameter.value = 1.0 maximum_parameter = FloatParameter('UUID-4') maximum_parameter.name = 'Minimum allowed' maximum_parameter.is_required = True maximum_parameter.precision = 3 maximum_parameter.minimum_allowed_value = -99999.0 maximum_parameter.maximum_allowed_value = 99999.0 maximum_parameter.help_text = 'The maximum allowable quantity per person. ' maximum_parameter.description = ( 'The <b>maximum</b> is the maximum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be more than 50l.') maximum_parameter.value = 1.0 default_parameter = FloatParameter('UUID-5') default_parameter.name = 'Default' default_parameter.is_required = True default_parameter.precision = 3 default_parameter.minimum_allowed_value = -99999.0 default_parameter.default_allowed_value = 99999.0 default_parameter.help_text = 'The default allowable quantity per person. ' default_parameter.description = ( 'The <b>default</b> is the default allowed quantity of the resource ' 'per person. For example you may indicate that the water ration per ' 'person per day should be 25l.') default_parameter.value = 1.0 parameters = [ name_parameter, description_parameter, unit_parameter, minimum_parameter, maximum_parameter, default_parameter ] parameter_container = ParameterContainer(parameters) widget = QWidget() layout = QGridLayout() layout.addWidget(parameter_container) widget.setLayout(layout) widget.setGeometry(0, 0, 500, 500) widget.show() new_parameters = parameter_container.get_parameters() for new_parameter in new_parameters: print new_parameter.name, new_parameter.value sys.exit(application.exec_())
class EntityEditorDialog(QDialog, MapperMixin): """ Dialog for editing entity attributes. """ addedModel = pyqtSignal(object) def __init__(self, entity, model=None, parent=None, manage_documents=True, collect_model=False, parent_entity=None, exclude_columns=[], plugin=None): """ Class constructor. :param entity: Entity object corresponding to a table object. :type entity: Entity :param model: Data object for loading data into the form widgets. If the model is set, then the editor dialog is assumed to be in edit mode. :type model: object :param parent: Parent widget that the form belongs to. :type parent: QWidget :param manage_documents: True if the dialog should provide controls for managing supporting documents. Only applicable if the entity allows for supporting documents to be attached. :type manage_documents: bool :param collect_model: If set to True only returns the filled form model without saving it to the database. :type collect_model: Boolean :param parent_entity: The parent entity of the editor :type parent_entity: Object :param exclude_columns: List of columns to be excluded if in a list. :type exclude_columns: List :return: If collect_model, returns SQLAlchemy Model """ QDialog.__init__(self, parent) self.entity_table_model = {} self.collection_suffix = self.tr('Collection') # Set minimum width self.setMinimumWidth(450) self.plugin = plugin # Flag for mandatory columns self.has_mandatory = False self.reload_form = False self._entity = entity self.edit_model = model self.column_widgets = OrderedDict() self._parent = parent self.exclude_columns = exclude_columns self.entity_tab_widget = None self._disable_collections = False self.filter_val = None self.parent_entity = parent_entity self.child_models = OrderedDict() self.entity_scroll_area = None self.entity_editor_widgets = OrderedDict() # Set notification layout bar self.vlNotification = QVBoxLayout() self.vlNotification.setObjectName('vlNotification') self._notifBar = NotificationBar(self.vlNotification) self.do_not_check_dirty = False # Set manage documents only if the entity supports documents if self._entity.supports_documents: self._manage_documents = manage_documents else: self._manage_documents = False # Setup entity model self._ent_document_model = None if self._entity.supports_documents: self.ent_model, self._ent_document_model = entity_model( self._entity, with_supporting_document=True) else: self.ent_model = entity_model(self._entity) if not model is None: self.ent_model = model MapperMixin.__init__(self, self.ent_model, entity) self.collect_model = collect_model self.register_column_widgets() try: if isinstance(parent._parent, EntityEditorDialog): # hide collections form child editor self._disable_collections = True except AttributeError: self._parent._parent = None # Set title editor_trans = self.tr('Editor') if self._entity.label is not None: if self._entity.label != '': title_str = self._entity.label else: title_str = format_name(self._entity.short_name) else: title_str = format_name(self._entity.short_name) self.title = u'{0} {1}'.format(title_str, editor_trans) self.setWindowTitle(self.title) self._init_gui() self.adjustSize() self._get_entity_editor_widgets() if isinstance(parent._parent, EntityEditorDialog): self.parent_entity = parent.parent_entity self.set_parent_values() # make the size smaller to differentiate from parent and as it # only has few tabs. self.adjustSize() self.attribute_mappers = self._attr_mapper_collection # Exception title for editor extension exceptions self._ext_exc_msg = self.tr( 'An error has occured while executing Python code in the editor ' 'extension:') # Register custom editor extension if specified self._editor_ext = entity_dlg_extension(self) if not self._editor_ext is None: self._editor_ext.post_init() # Initialize CascadingFieldContext objects self._editor_ext.connect_cf_contexts() def _init_gui(self): # Setup base elements self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName('glMain') self.gridLayout.addLayout(self.vlNotification, 0, 0, 1, 1) QApplication.processEvents() column_widget_area = self._setup_columns_content_area() self.gridLayout.addWidget(column_widget_area, 1, 0, 1, 1) QApplication.processEvents() # Add notification for mandatory columns if applicable next_row = 2 if self.has_mandatory: self.required_fields_lbl = QLabel(self) msg = self.tr('Please fill out all required (*) fields.') msg = self._highlight_asterisk(msg) self.required_fields_lbl.setText(msg) self.gridLayout.addWidget(self.required_fields_lbl, next_row, 0, 1, 2) # Bump up row reference next_row += 1 self.buttonBox = QDialogButtonBox(self) self.buttonBox.setObjectName('buttonBox') self.gridLayout.addWidget(self.buttonBox, next_row, 0, 1, 1) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Save) if self.edit_model is None: if not self.collect_model: self.save_new_button = QPushButton( QApplication.translate('EntityEditorDialog', 'Save and New')) self.buttonBox.addButton(self.save_new_button, QDialogButtonBox.ActionRole) # edit model, collect model # adding new record for child # Saving in parent editor if not isinstance(self._parent._parent, EntityEditorDialog): # adding a new record if self.edit_model is None: # saving when digitizing. if self.collect_model: self.buttonBox.accepted.connect(self.on_model_added) # saving parent editor else: self.buttonBox.accepted.connect(self.save_parent_editor) self.save_new_button.clicked.connect(self.save_and_new) # updating existing record else: if not self.collect_model: # updating existing record of the parent editor self.buttonBox.accepted.connect(self.save_parent_editor) else: self.buttonBox.accepted.connect(self.on_model_added) # Saving in child editor else: # save and new record if self.edit_model is None: self.buttonBox.accepted.connect(self.on_child_saved) self.save_new_button.clicked.connect( lambda: self.on_child_saved(True)) else: # When updating an existing child editor save to the db self.buttonBox.accepted.connect(self.on_child_saved) # self.buttonBox.accepted.connect(self.submit) self.buttonBox.rejected.connect(self.cancel) @property def notification_bar(self): """ :return: Returns the dialog's notification bar. :rtype: NotificationBar """ return self._notifBar def save_parent_editor(self): """ Saves the parent editor and its children. """ self.submit() self.save_children() def set_parent_values(self): """ Sets the parent display column for the child. """ if self.parent_entity is None: return for col in self._entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': parent_entity = col.parent if parent_entity == self.parent_entity: self.parent_widgets_value_setter(self._parent._parent, col) def parent_widgets_value_setter(self, parent, col): """ Finds and sets the value from parent widget and set it to the column widget of a child using the child column. :param parent: The parent widget :type parent: QWidget :param col: The child column object :type col: Object """ for parent_col, parent_widget in parent.column_widgets.iteritems(): if parent_col.name == col.name: self.single_parent_value_setter(col, parent_widget) break if parent_col.name in col.entity_relation.display_cols: self.single_parent_value_setter(col, parent_widget) break def single_parent_value_setter(self, col, parent_widget): """ Gets value from parent widget and set it to the column widget of a child using the child column. :param parent: The parent widget :type parent: QWidget :param col: The child column object :type col: Object """ local_widget = self.column_widgets[col] local_widget.show_clear_button() self.filter_val = parent_widget.text() local_widget.setText(self.filter_val) def save_and_new(self): """ A slot raised when Save and New button is click. It saves the form without showing a success message. Then it sets reload_form property to True so that entity_browser can re-load the form. """ from stdm.ui.entity_browser import (EntityBrowserWithEditor) self.submit(False, True) self.save_children() if self.is_valid: self.addedModel.emit(self.model()) self.setModel(self.ent_model()) self.clear() self.child_models.clear() for index in range(0, self.entity_tab_widget.count() - 1): if isinstance(self.entity_tab_widget.widget(index), EntityBrowserWithEditor): child_browser = self.entity_tab_widget.widget(index) child_browser.remove_rows() def on_model_added(self): """ A slot raised when a form is submitted with collect model set to True. There will be no success message and the form does not close. """ self.submit(True) self.addedModel.emit(self.model()) def closeEvent(self, event): ''' Raised when a request to close the window is received. Check the dirty state of input controls and prompt user to save if dirty. ''' if self.do_not_check_dirty: event.accept() return isDirty, userResponse = self.checkDirty() if isDirty: if userResponse == QMessageBox.Yes: # We need to ignore the event so that validation and # saving operations can be executed event.ignore() self.submit() elif userResponse == QMessageBox.No: event.accept() elif userResponse == QMessageBox.Cancel: event.ignore() else: event.accept() def on_child_saved(self, save_and_new=False): """ A slot raised when the save or save and new button is clicked. It sets the child_models dictionary of the parent when saved. :param save_and_new: A boolean indicating the save and new button is clicked to trigger the slot. :type save_and_new: Boolean """ if self.parent_entity is None: return self.submit(True) insert_pos = self._parent.tbEntity.model().rowCount() + 1 # Save to parent editor so that it is persistent. self._parent._parent.child_models[insert_pos, self._entity] = \ self.model() self.addedModel.emit(self.model()) if not save_and_new: self.accept() else: if self.is_valid: # self.addedModel.emit(self.model()) self.setModel(self.ent_model()) self.clear() self.set_parent_values() def save_children(self): """ Saves children models into the database by assigning the the id of the parent for foreign key column. """ if len(self.child_models) < 1: return children_obj = [] for row_entity, model in self.child_models.iteritems(): row_pos = row_entity[0] entity = row_entity[1] ent_model = entity_model(entity) entity_obj = ent_model() for col in entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': if col.parent.name == self._entity.name: setattr(model, col.name, self.model().id) children_obj.append(model) entity_obj.saveMany(children_obj) def register_column_widgets(self): """ Registers the column widgets. """ # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) self.scroll_widget_contents = QWidget() self.scroll_widget_contents.setObjectName('scrollAreaWidgetContents') for c in self._entity.columns.values(): if c.name in self.exclude_columns: continue if not c.name in columns and not isinstance(c, VirtualColumn): continue # Get widget factory column_widget = ColumnWidgetRegistry.create( c, self.scroll_widget_contents, host=self) self.column_widgets[c] = column_widget def _setup_columns_content_area(self): # Only use this if entity supports documents # self.entity_tab_widget = None self.doc_widget = None self.entity_scroll_area = QScrollArea(self) self.entity_scroll_area.setFrameShape(QFrame.NoFrame) self.entity_scroll_area.setWidgetResizable(True) self.entity_scroll_area.setObjectName('scrollArea') # Grid layout for controls self.gl = QGridLayout(self.scroll_widget_contents) self.gl.setObjectName('gl_widget_contents') # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) # Iterate entity column and assert if they exist row_id = 0 for c, column_widget in self.column_widgets.iteritems(): if c.name in self.exclude_columns: continue if not c.name in columns and not isinstance(c, VirtualColumn): continue if column_widget is not None: header = c.ui_display() self.c_label = QLabel(self.scroll_widget_contents) # Format label text if it is a mandatory field if c.mandatory: header = u'{0} *'.format(c.ui_display()) # Highlight asterisk header = self._highlight_asterisk(header) self.c_label.setText(header) self.gl.addWidget(self.c_label, row_id, 0, 1, 1) self.column_widget = column_widget self.gl.addWidget(self.column_widget, row_id, 1, 1, 1) # Add user tip if specified for the column configuration if c.user_tip: self.tip_lbl = UserTipLabel(user_tip=c.user_tip) self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1) if c.mandatory and not self.has_mandatory: self.has_mandatory = True col_name = c.name # Replace name accordingly based on column type if isinstance(c, MultipleSelectColumn): col_name = c.model_attribute_name # Add widget to MapperMixin collection self.addMapping(col_name, self.column_widget, c.mandatory, pseudoname=c.ui_display()) # Bump up row_id row_id += 1 self.entity_scroll_area.setWidget(self.scroll_widget_contents) if self.entity_tab_widget is None: self.entity_tab_widget = QTabWidget(self) # Check if there are children and add foreign key browsers # Add primary tab if necessary self._add_primary_attr_widget() if not self._disable_collections: ch_entities = self.children_entities() for col, ch in ch_entities.iteritems(): if hasattr(col.entity_relation, 'show_in_parent'): if col.entity_relation.show_in_parent != '0': self._add_fk_browser(ch, col) else: self._add_fk_browser(ch, col) # Add tab widget if entity supports documents if self._entity.supports_documents: self.doc_widget = SupportingDocumentsWidget( self._entity.supporting_doc, self._ent_document_model, self) # Map the source document manager object self.addMapping('documents', self.doc_widget.source_document_manager) # # # Add attribute tab # self._add_primary_attr_widget() # Add supporting documents tab self.entity_tab_widget.addTab(self.doc_widget, self.tr('Supporting Documents')) # Return the correct widget if not self.entity_tab_widget is None: return self.entity_tab_widget return self.entity_scroll_area def _add_primary_attr_widget(self): # Check if the primary entity # exists and add if it does not pr_txt = self.tr('Primary') if not self.entity_tab_widget is None: tab_txt = self.entity_tab_widget.tabText(0) if not tab_txt == pr_txt: self.entity_tab_widget.addTab(self.entity_scroll_area, pr_txt) def _add_fk_browser(self, child_entity, column): # Create and add foreign key # browser to the collection from stdm.ui.entity_browser import (EntityBrowserWithEditor) attr = u'{0}_collection'.format(child_entity.name) # Return if the attribute does not exist if not hasattr(self._model, attr): return entity_browser = EntityBrowserWithEditor(child_entity, self, MANAGE, False, plugin=self.plugin) entity_browser.buttonBox.setVisible(False) entity_browser.record_filter = [] if len(column.label) > 2: column_label = column.label else: column_label = format_name(column.name) self.entity_tab_widget.addTab(entity_browser, u'{0}'.format(column_label)) self.set_filter(child_entity, entity_browser) def set_filter(self, entity, browser): col = self.filter_col(entity) child_model = entity_model(entity) child_model_obj = child_model() col_obj = getattr(child_model, col.name) if self.model() is not None: if self.model().id is None: browser.filtered_records = [] else: browser.filtered_records = child_model_obj.queryObject( ).filter(col_obj == self.model().id).all() if self.edit_model is not None: browser.filtered_records = child_model_obj.queryObject().filter( col_obj == self.edit_model.id).all() if self.edit_model is None and self.model() is None: browser.filtered_records = [] def filter_col(self, child_entity): for col in child_entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': parent_entity = col.parent if parent_entity == self._entity: return col def children_entities(self): """ :return: Returns a list of children entities that refer to the main entity as the parent. :rtype: OrderedDict """ child_columns = OrderedDict() for ch in self._entity.children(): if ch.TYPE_INFO == Entity.TYPE_INFO: for col in ch.columns.values(): if hasattr(col, 'entity_relation'): if col.parent.name == self._entity.name: child_columns[col] = ch return child_columns def document_widget(self): """ :return: Returns the widget for managing the supporting documents for an entity if enabled. :rtype: SupportingDocumentsWidget """ return self.doc_widget def source_document_manager(self): """ :return: Returns an instance of the SourceDocumentManager only if supporting documents are enabled for the given entity. Otherwise, None if supporting documents are not enabled. :rtype: SourceDocumentManager """ if self.doc_widget is None: return None return self.doc_widget.source_document_manager def _highlight_asterisk(self, text): # Highlight asterisk in red c = '*' # Do not format if there is no asterisk if text.find(c) == -1: return text asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>' text = text.replace(c, asterisk_highlight) return u'<html><head/><body><p>{0}</p></body></html>'.format(text) def _custom_validate(self): """ Override of the MapperMixin which enables custom editor extensions to inject additional validation before saving form data. :return: Return True if the validation was successful, otherwise False. :rtype: bool """ if not self._editor_ext is None: return self._editor_ext.validate() # Return True if there is no custom editor extension specified return True def _post_save(self, model): """ Include additional post-save logic by custom extensions. :param model: SQLAlchemy model :type model: object """ if not self._editor_ext is None: self._editor_ext.post_save(model) def _get_entity_editor_widgets(self): """ Gets entity editor widgets and appends them to a dictionary """ if self.entity_tab_widget: tab_count = self.entity_tab_widget.count() for i in range(tab_count): tab_object = self.entity_tab_widget.widget(i) tab_text = self.entity_tab_widget.tabText(i) self.entity_editor_widgets[tab_text] = tab_object else: self.entity_editor_widgets['no_tab'] = self.entity_scroll_area
def __init__(self, parent=None): QWidget.__init__(self, parent) uicLoad("ffado/mixer/dummy", self)
def __init__(self, iface): QWidget.__init__(self) self.iface = iface self.canvas = self.iface.mapCanvas() self.algorithm = ('invdist', 'average', 'nearest', 'datametrics') self.datametrics = ('minimum', 'maximum', 'range') self.setupUi(self) BasePluginWidget.__init__(self, self.iface, "gdal_grid") self.outSelector.setType(self.outSelector.FILE) self.extentSelector.setCanvas(self.canvas) #self.extentSelector.stop() # set the default QSpinBoxes and QProgressBar value self.widthSpin.setValue(3000) self.heightSpin.setValue(3000) self.invdistPowerSpin.setValue(2.0) self.outputFormat = Utils.fillRasterOutputFormat() self.lastEncoding = Utils.getLastUsedEncoding() self.setParamsStatus([ (self.inSelector, SIGNAL("filenameChanged()")), (self.outSelector, SIGNAL("filenameChanged()")), (self.zfieldCombo, SIGNAL("currentIndexChanged(int)"), self.zfieldCheck), (self.algorithmCombo, SIGNAL("currentIndexChanged(int)"), self.algorithmCheck), (self.stackedWidget, None, self.algorithmCheck), ([ self.invdistPowerSpin, self.invdistSmothingSpin, self.invdistRadius1Spin, self.invdistRadius2Spin, self.invdistAngleSpin, self.invdistNoDataSpin ], SIGNAL("valueChanged(double)")), ([self.invdistMaxPointsSpin, self.invdistMinPointsSpin], SIGNAL("valueChanged(int)")), ([ self.averageRadius1Spin, self.averageRadius2Spin, self.averageAngleSpin, self.averageNoDataSpin ], SIGNAL("valueChanged(double)")), (self.averageMinPointsSpin, SIGNAL("valueChanged(int)")), ([ self.nearestRadius1Spin, self.nearestRadius2Spin, self.nearestAngleSpin, self.nearestNoDataSpin ], SIGNAL("valueChanged(double)")), (self.datametricsCombo, SIGNAL("currentIndexChanged(int)")), ([ self.datametricsRadius1Spin, self.datametricsRadius2Spin, self.datametricsAngleSpin, self.datametricsNoDataSpin ], SIGNAL("valueChanged(double)")), (self.datametricsMinPointsSpin, SIGNAL("valueChanged(int)")), (self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentGroup), ([self.widthSpin, self.heightSpin], SIGNAL("valueChanged(int)"), self.resizeGroupBox) ]) self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit) self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit) self.connect(self.inSelector, SIGNAL("layerChanged()"), self.fillFieldsCombo) self.connect(self.extentGroup, SIGNAL("toggled(bool)"), self.onExtentCheckedChanged)
def __init__(self, manager, name, image=None, message=None, position=None, size=None, high_quality=False): super(PreviewWindow, self).__init__() self.setObjectName("Preview window {}".format(name)) self.setWindowTitle(name) self.manager = manager desktop = QApplication.instance().desktop() if self.maxsize: self.maxsize = QSize(*self.maxsize) else: self.maxsize = desktop.screenGeometry(desktop.screenNumber(self)).size() * 0.95 self.setMinimumSize(*self.minsize) self.setMaximumSize(self.maxsize) self.image = None self.original = None self.message = message self.scale = 1. self.rotation = 0 self.quality = Qt.SmoothTransformation if high_quality else Qt.FastTransformation self.fixed_size = size self.scrollarea = PreviewScrollArea() self.scrollarea.setFrameStyle(0) self.scrollarea.setFocusPolicy(Qt.NoFocus) layout = QGridLayout() layout.setMargin(0) layout.setContentsMargins(0,0,0,0) self.setLayout(layout) layout.addWidget(self.scrollarea, 0, 0) self.preview = QLabel() self.preview.setMouseTracking(False) self.preview.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.scrollarea.setWidget(self.preview) self.message_label = QLabel(" ") self.layout().addWidget(self.message_label, 0, 0, Qt.AlignTop) self.message_label.setStyleSheet("QLabel {color:black;background:rgba(255,255,255,32)}") self.message_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.message_label.setText("") shadow = QGraphicsDropShadowEffect() shadow.setBlurRadius(4) shadow.setColor(Qt.white) shadow.setOffset(0,0) self.message_label.setGraphicsEffect(shadow) self.blink_widget = QWidget() self.blink_widget.hide() self.blink_widget.setStyleSheet("border:3px solid red") self.blink_timer = QTimer() self.blink_timer.setInterval(1000) self.blink_timer.timeout.connect(self.blink_) layout.addWidget(self.blink_widget, 0, 0) self.setImage(image, show=False) if image is not None and not size: size = self.autoSize() if size: self.resize(*size) if position == 'cursor': position = (QCursor.pos().x() - self.size().width()//2, QCursor.pos().y() - self.size().height()//2) if position: self.move(*position) self.showNormal()
def __init__(self, parent): QMainWindow.__init__(self, parent) self._ert = ERT.ert """:type: ert.enkf.enkf_main.EnKFMain""" key_manager = self._ert.getKeyManager() """:type: ert.enkf.key_manager.KeyManager """ self.setMinimumWidth(850) self.setMinimumHeight(650) self.setWindowTitle("Plotting") self.activateWindow() self._plot_customizer = PlotCustomizer(self, self._ert.plotConfig()) def plotConfigCreator(key): return PlotConfigFactory.createPlotConfigForKey(self._ert, key) self._plot_customizer.setPlotConfigCreator(plotConfigCreator) self._plot_customizer.settingsChanged.connect(self.keySelected) self._central_tab = QTabWidget() self._central_tab.currentChanged.connect(self.currentPlotChanged) central_widget = QWidget() central_layout = QVBoxLayout() central_layout.setContentsMargins(0, 0, 0, 0) central_widget.setLayout(central_layout) central_layout.addWidget(self._central_tab) self.setCentralWidget(central_widget) self._plot_widgets = [] """:type: list of PlotWidget""" self._data_gatherers = [] """:type: list of PlotDataGatherer """ summary_gatherer = self.createDataGatherer( PDG.gatherSummaryData, key_manager.isSummaryKey, refcaseGatherFunc=PDG.gatherSummaryRefcaseData, observationGatherFunc=PDG.gatherSummaryObservationData, historyGatherFunc=PDG.gatherSummaryHistoryData) gen_data_gatherer = self.createDataGatherer( PDG.gatherGenDataData, key_manager.isGenDataKey, observationGatherFunc=PDG.gatherGenDataObservationData) gen_kw_gatherer = self.createDataGatherer(PDG.gatherGenKwData, key_manager.isGenKwKey) custom_kw_gatherer = self.createDataGatherer(PDG.gatherCustomKwData, key_manager.isCustomKwKey) self.addPlotWidget(ENSEMBLE, plots.plotEnsemble, [summary_gatherer, gen_data_gatherer]) self.addPlotWidget(STATISTICS, plots.plotStatistics, [summary_gatherer, gen_data_gatherer]) self.addPlotWidget(HISTOGRAM, plots.plotHistogram, [gen_kw_gatherer, custom_kw_gatherer]) self.addPlotWidget(GAUSSIAN_KDE, plots.plotGaussianKDE, [gen_kw_gatherer, custom_kw_gatherer]) self.addPlotWidget(DISTRIBUTION, plots.plotDistribution, [gen_kw_gatherer, custom_kw_gatherer]) self.addPlotWidget(CROSS_CASE_STATISTICS, plots.plotCrossCaseStatistics, [gen_kw_gatherer, custom_kw_gatherer]) data_types_key_model = DataTypeKeysListModel(self._ert) self._data_type_keys_widget = DataTypeKeysWidget(data_types_key_model) self._data_type_keys_widget.dataTypeKeySelected.connect( self.keySelected) self.addDock("Data types", self._data_type_keys_widget) current_case = getCurrentCaseName() self._case_selection_widget = CaseSelectionWidget(current_case) self._case_selection_widget.caseSelectionChanged.connect( self.keySelected) self.addDock("Plot case", self._case_selection_widget) current_plot_widget = self._plot_widgets[ self._central_tab.currentIndex()] current_plot_widget.setActive() self._data_type_keys_widget.selectDefault() self._updateCustomizer(current_plot_widget)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self.init()
def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) """ Set GUI to track mouse """ QWidget.setMouseTracking(self, True) """ Dynamixel bus TODO: add other motors here as needed with their correct address""" self.dxlbus = DXL_BUS(DEVICENAME, BAUDRATE) port_num = self.dxlbus.port() base = DXL_MX(port_num, 1) shld = DXL_MX(port_num, 2) elbw = DXL_MX(port_num, 3) wrst = DXL_AX(port_num, 4) wrst2 = DXL_AX(port_num, 5) wrst3 = DXL_XL(port_num, 6) grip = DXL_XL(port_num, 7) """Objects Using Other Classes""" self.kinect = Kinect() self.rexarm = Rexarm((base, shld, elbw, wrst, wrst2, wrst3), grip) self.tp = TrajectoryPlanner(self.rexarm) self.sm = StateMachine(self.rexarm, self.tp, self.kinect) """ Attach Functions to Buttons & Sliders TODO: NAME AND CONNECT BUTTONS AS NEEDED """ self.ui.btn_estop.clicked.connect(self.estop) self.ui.btnUser1.setText("Calibrate") self.ui.btnUser1.clicked.connect( partial(self.sm.set_next_state, "calibrate")) self.ui.btnUser2.setText("Waypoint") self.ui.btnUser2.clicked.connect( partial(self.sm.set_next_state, "waypoint")) self.ui.btnUser3.setText("Teach") self.ui.btnUser3.clicked.connect( partial(self.sm.set_next_state, "teach")) self.ui.btnUser4.setText("Record") self.ui.btnUser4.clicked.connect( partial(self.sm.set_next_state, "record")) self.ui.btnUser5.setText("Repeat") self.ui.btnUser5.clicked.connect( partial(self.sm.set_next_state, "repeat")) self.ui.btn_task1.setText("Pick n Stack") self.ui.btn_task1.clicked.connect(partial(self.sm.set_next_state, "IK")) self.ui.btnUser6.setText("Click and Place") self.ui.btnUser6.clicked.connect( partial(self.sm.set_next_state, "clickgrab")) self.ui.btnUser7.setText("Open Gripper") self.ui.btnUser7.clicked.connect( partial(self.sm.set_next_state, "open_gripper")) self.ui.btnUser8.setText("Close Gripper") self.ui.btnUser8.clicked.connect( partial(self.sm.set_next_state, "close_gripper")) self.ui.btnUser9.setText("Incline") self.ui.btnUser9.clicked.connect( partial(self.sm.set_next_state, "incline")) self.ui.btn_task2.setText("Line Em Up") self.ui.btn_task2.clicked.connect( partial(self.sm.set_next_state, "color_sort")) self.ui.btn_task3.setText("Stack Em High") self.ui.btn_task3.clicked.connect( partial(self.sm.set_next_state, "color_stack")) self.ui.btn_task4.setText("Block Mover") self.ui.btn_task4.clicked.connect( partial(self.sm.set_next_state, "square")) self.ui.sldrBase.valueChanged.connect(self.sliderChange) self.ui.sldrShoulder.valueChanged.connect(self.sliderChange) self.ui.sldrElbow.valueChanged.connect(self.sliderChange) self.ui.sldrWrist.valueChanged.connect(self.sliderChange) self.ui.sldrWrist2.valueChanged.connect(self.sliderChange) self.ui.sldrWrist3.valueChanged.connect(self.sliderChange) #self.ui.sldrGrip1.valueChanged.connect(self.sliderChange) self.ui.sldrMaxTorque.valueChanged.connect(self.sliderChange) self.ui.sldrSpeed.valueChanged.connect(self.sliderChange) self.ui.chk_directcontrol.stateChanged.connect(self.directControlChk) self.ui.rdoutStatus.setText("Waiting for input") """initalize manual control off""" self.ui.SliderFrame.setEnabled(False) """initalize rexarm""" self.rexarm.initialize() """Setup Threads""" self.videoThread = VideoThread(self.kinect) self.videoThread.updateFrame.connect(self.setImage) self.videoThread.start() self.logicThread = LogicThread(self.sm) self.logicThread.start() self.displayThread = DisplayThread(self.rexarm, self.sm) self.displayThread.updateJointReadout.connect(self.updateJointReadout) self.displayThread.updateEndEffectorReadout.connect( self.updateEndEffectorReadout) self.displayThread.updateStatusMessage.connect( self.updateStatusMessage) self.displayThread.start() """ Setup Timer this runs the trackMouse function every 50ms """ self._timer = QTimer(self) self._timer.timeout.connect(self.trackMouse) self._timer.start(50)
def __init__(self, parent=None): super(FeatureFormWidget, self).__init__(parent) self.setupUi(self) toolbar = QToolBar() size = QSize(48, 48) toolbar.setIconSize(size) style = Qt.ToolButtonTextUnderIcon toolbar.setToolButtonStyle(style) self.actionDelete = toolbar.addAction(QIcon(":/icons/delete"), "Delete") self.actionDelete.triggered.connect(self.delete_feature) label = 'Required fields marked in <b style="background-color:rgba(255, 221, 48,150)">yellow</b>' self.missingfieldsLabel = QLabel(label) self.missingfieldsLabel.hide() self.missingfieldaction = toolbar.addWidget(self.missingfieldsLabel) titlespacer = QWidget() titlespacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(titlespacer) self.titlellabel = QLabel(label) self.titlellabel.setProperty("headerlabel", True) self.titlelabelaction = toolbar.addWidget(self.titlellabel) spacer = QWidget() spacer2 = QWidget() spacer2.setMinimumWidth(20) spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) spacer2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) toolbar.addWidget(spacer) self.actionCancel = toolbar.addAction(QIcon(":/icons/cancel"), "Cancel") toolbar.addWidget(spacer2) self.actionSave = toolbar.addAction(QIcon(":/icons/save"), "Save") self.actionSave.triggered.connect(self.save_feature) self.layout().insertWidget(0, toolbar) self.flickwidget = FlickCharm() self.flickwidget.activateOn(self.scrollArea) self.featureform = None self.values = {} self.config = {} self.feature = None
class PreviewWindow(QFrame): minsize = (32, 32) maxsize = None last_save_dir = "" raise_window = False key_signal = pyqtSignal(int, int, int) move_signal = pyqtSignal() def __init__(self, manager, name, image=None, message=None, position=None, size=None, high_quality=False): super(PreviewWindow, self).__init__() self.setObjectName("Preview window {}".format(name)) self.setWindowTitle(name) self.manager = manager desktop = QApplication.instance().desktop() if self.maxsize: self.maxsize = QSize(*self.maxsize) else: self.maxsize = desktop.screenGeometry(desktop.screenNumber(self)).size() * 0.95 self.setMinimumSize(*self.minsize) self.setMaximumSize(self.maxsize) self.image = None self.original = None self.message = message self.scale = 1. self.rotation = 0 self.quality = Qt.SmoothTransformation if high_quality else Qt.FastTransformation self.fixed_size = size self.scrollarea = PreviewScrollArea() self.scrollarea.setFrameStyle(0) self.scrollarea.setFocusPolicy(Qt.NoFocus) layout = QGridLayout() layout.setMargin(0) layout.setContentsMargins(0,0,0,0) self.setLayout(layout) layout.addWidget(self.scrollarea, 0, 0) self.preview = QLabel() self.preview.setMouseTracking(False) self.preview.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.scrollarea.setWidget(self.preview) self.message_label = QLabel(" ") self.layout().addWidget(self.message_label, 0, 0, Qt.AlignTop) self.message_label.setStyleSheet("QLabel {color:black;background:rgba(255,255,255,32)}") self.message_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.message_label.setText("") shadow = QGraphicsDropShadowEffect() shadow.setBlurRadius(4) shadow.setColor(Qt.white) shadow.setOffset(0,0) self.message_label.setGraphicsEffect(shadow) self.blink_widget = QWidget() self.blink_widget.hide() self.blink_widget.setStyleSheet("border:3px solid red") self.blink_timer = QTimer() self.blink_timer.setInterval(1000) self.blink_timer.timeout.connect(self.blink_) layout.addWidget(self.blink_widget, 0, 0) self.setImage(image, show=False) if image is not None and not size: size = self.autoSize() if size: self.resize(*size) if position == 'cursor': position = (QCursor.pos().x() - self.size().width()//2, QCursor.pos().y() - self.size().height()//2) if position: self.move(*position) self.showNormal() def setImage(self, image, show=True, scale=None, blink=False): if image is None: return self.original = image if isinstance(image, QImage): image = QPixmap.fromImage(image) elif isinstance(image, QPixmap): pass else: image = array_to_pixmap(image) self.image = image if not scale: scale = self.scale if image.width()*scale > self.maxsize.width(): scale = self.maxsize.width() / image.width() if image.height()*scale > self.maxsize.height(): scale = self.maxsize.height() / image.height() self.setZoom(scale) if self.message is not None: self.message_label.setText(self.message) if blink: self.blink(True) if show: self.setShown(True) if self.raise_window: self.raise_() def closeEvent(self, event): self.scale = 1.0 self.fixed_size = None def setImageAndParams(self, image, show=True, scale=None, position=None, size=None, hq=None, message=None, blink=False): if size: self.fixed_size = size if position: self.move(*position) if hq is not None: if hq: self.quality = Qt.SmoothTransformation else: self.quality = Qt.FastTransformation if message is not None: self.message = message self.setImage(image, show=show, scale=scale, blink=blink) def setZoom(self, scale): self.setParams(scale=scale) def setRotation(self, rotation): self.setParams(rotation=rotation) def setParams(self, scale=None, rotation=None): assert isinstance(self.image, QPixmap) if scale is None: scale = self.scale if rotation is None: rotation = self.rotation if scale != 1.0 or rotation: transform = QTransform().rotate(rotation).scale(scale,scale) pixmap = self.image.transformed(transform, self.quality) else: pixmap = self.image w = pixmap.width() h = pixmap.height() self.scale = scale self.rotation = rotation self.preview.setPixmap(pixmap) self.preview.setFixedSize(pixmap.size()) if not self.fixed_size: self.resize(w, h) def autoSize(self): size = self.image.size() w = size.width() h = size.height() return w, h def wheelEvent(self, event): assert isinstance(event, QWheelEvent) event.accept() if event.delta() > 0: s = 1.1 else: s = 1 / 1.1 self.setZoom(s * self.scale) scrollX = self.scrollarea.horizontalScrollBar().value() posX = event.x() newX = s * (scrollX + posX) - posX self.scrollarea.horizontalScrollBar().setValue(int(newX)) scrollY = self.scrollarea.verticalScrollBar().value() posY = event.y() newY = s * (scrollY + posY) - posY self.scrollarea.verticalScrollBar().setValue(int(newY)) self.blink(False) def mousePressEvent(self, event): assert isinstance(event, QMouseEvent) self.key_signal.emit(KEY_MOUSE, event.x(), event.y()) self.blink(False) event.accept() def keyPressEvent(self, event): assert isinstance(event, QKeyEvent) self.key_signal.emit(int(event.key()), 0, 0) self.blink(False) if event.key() == Qt.Key_Escape: self.close() event.accept() def moveEvent(self, event): self.move_signal.emit() def contextMenuEvent(self, event): assert isinstance(event, QContextMenuEvent) self.blink(False) menu = QMenu() copy = menu.addAction("Copy to clipboard") reset = menu.addAction("Reset view") hq = menu.addAction("High quality") hq.setCheckable(True) if self.quality == Qt.SmoothTransformation: hq.setChecked(True) fixed = menu.addAction("Fixed size") fixed.setCheckable(True) if self.fixed_size: fixed.setChecked(True) rotate_right = menu.addAction("Rotate +") rotate_left = menu.addAction("Rotate -") save = menu.addAction("Save...") quit = menu.addAction("Close") action = menu.exec_(self.mapToGlobal(event.pos())) if action == quit: self.close() elif action == reset: self.setParams(1,0) elif action == hq: if self.quality == Qt.SmoothTransformation: self.quality = Qt.FastTransformation else: self.quality = Qt.SmoothTransformation self.setZoom(self.scale) elif action == rotate_right: rotation = (self.rotation + 90) % 360 self.setRotation(rotation) elif action == rotate_left: rotation = (self.rotation + 270) % 360 self.setRotation(rotation) elif action == save: filename, filter = QFileDialog.getSaveFileNameAndFilter(self, "Save image...", filter="*.png;;*.jpg;;*.bmp;;*.tiff;;*.gif", directory=self.last_save_dir) if filename: try: if not str(filename).endswith(filter[1:]): filename = filename + filter[1:] PreviewWindow.last_save_dir = path.dirname(str(filename)) success = self.image.save(filename, quality=100) if not success: raise Exception("unknown error") except Exception as e: QMessageBox.critical(self, "Saving error", "Cannot save.\nError: {}".format(e.message)) print("Saving error:", e) elif action == fixed: if self.fixed_size: self.fixed_size = None else: self.fixed_size = self.size() elif action == copy: print("copy") clipboard = QApplication.instance().clipboard() clipboard.setPixmap(self.image) def blink(self, enable): if enable: self.blink_timer.start() else: self.blink_timer.stop() self.blink_widget.hide() @pyqtSlot() def blink_(self): if self.blink_widget.isHidden(): self.blink_widget.show() else: self.blink_widget.hide()
def __init__(self, layerStackModel, parent, labelsink=None, crosshair=True, syncAlongAxes=(0, 1)): super(VolumeEditor, self).__init__(parent=parent) self._sync_along = tuple(syncAlongAxes) ## ## properties ## self._showDebugPatches = False self._showTileProgress = True ## ## base components ## self.layerStack = layerStackModel self.posModel = PositionModel(self) self.brushingModel = BrushingModel() self.cropModel = CropExtentsModel(self) self.imageScenes = [ ImageScene2D(self.posModel, (0, 1, 4), swapped_default=True), ImageScene2D(self.posModel, (0, 2, 4)), ImageScene2D(self.posModel, (0, 3, 4)) ] self.imageViews = [ ImageView2D(parent, self.cropModel, self.imageScenes[i]) for i in [0, 1, 2] ] self.imageViews[0].focusChanged.connect( lambda arg=0: self.lastImageViewFocus(arg)) self.imageViews[1].focusChanged.connect( lambda arg=1: self.lastImageViewFocus(arg)) self.imageViews[2].focusChanged.connect( lambda arg=2: self.lastImageViewFocus(arg)) self._lastImageViewFocus = 0 if not crosshair: for view in self.imageViews: view._crossHairCursor.enabled = False self.imagepumps = self._initImagePumps() self.view3d = self._initView3d() if useVTK else QWidget() names = ['x', 'y', 'z'] for scene, name, pump in zip(self.imageScenes, names, self.imagepumps): scene.setObjectName(name) scene.stackedImageSources = pump.stackedImageSources self.cacheSize = 50 ## ## interaction ## # event switch self.eventSwitch = EventSwitch(self.imageViews) # navigation control v3d = self.view3d if useVTK else None self.navCtrl = NavigationController(self.imageViews, self.imagepumps, self.posModel, view3d=v3d) self.navInterpret = NavigationInterpreter(self.navCtrl) # brushing control if crosshair: self.crosshairController = CrosshairController( self.brushingModel, self.imageViews) self.brushingController = BrushingController(self.brushingModel, self.posModel, labelsink) self.brushingInterpreter = BrushingInterpreter(self.navCtrl, self.brushingController) for v in self.imageViews: self.brushingController._brushingModel.brushSizeChanged.connect( v._sliceIntersectionMarker._set_diameter) # thresholding control self.thresInterpreter = ThresholdingInterpreter( self.navCtrl, self.layerStack, self.posModel) # initial interaction mode self.eventSwitch.interpreter = self.navInterpret # By default, don't show cropping controls self.showCropLines(False) ## ## connect ## self.posModel.timeChanged.connect(self.navCtrl.changeTime) self.posModel.slicingPositionChanged.connect( self.navCtrl.moveSlicingPosition) if crosshair: self.posModel.cursorPositionChanged.connect( self.navCtrl.moveCrosshair) self.posModel.slicingPositionSettled.connect( self.navCtrl.settleSlicingPosition) self.layerStack.layerAdded.connect(self._onLayerAdded) self.parent = parent
def __init__(self, dialog): super(FontsColors, self).__init__(dialog) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.scheme = SchemeSelector(self) layout.addWidget(self.scheme) self.printScheme = QCheckBox() layout.addWidget(self.printScheme) hbox = QHBoxLayout() self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) self.tree.setAnimated(True) self.stack = QStackedWidget(self) hbox.addWidget(self.tree) hbox.addWidget(self.stack) layout.addLayout(hbox) hbox = QHBoxLayout() self.fontLabel = QLabel() self.fontChooser = QFontComboBox() self.fontSize = QDoubleSpinBox() self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) hbox.addWidget(self.fontLabel) hbox.addWidget(self.fontChooser, 1) hbox.addWidget(self.fontSize) layout.addLayout(hbox) # add the items to our list self.baseColorsItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStylesItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStyles = {} for name in textformats.defaultStyles: self.defaultStyles[name] = i = QTreeWidgetItem() self.defaultStylesItem.addChild(i) i.name = name self.defaultStylesItem.setExpanded(True) self.allStyles = {} for group, styles in ly.colorize.default_mapping(): i = QTreeWidgetItem() children = {} self.allStyles[group] = (i, children) self.tree.addTopLevelItem(i) i.group = group for name, base, clss in styles: j = QTreeWidgetItem() j.name = name j.base = base i.addChild(j) children[name] = j self.baseColorsWidget = BaseColors(self) self.customAttributesWidget = CustomAttributes(self) self.emptyWidget = QWidget(self) self.stack.addWidget(self.baseColorsWidget) self.stack.addWidget(self.customAttributesWidget) self.stack.addWidget(self.emptyWidget) self.tree.currentItemChanged.connect(self.currentItemChanged) self.tree.setCurrentItem(self.baseColorsItem) self.scheme.currentChanged.connect(self.currentSchemeChanged) self.scheme.changed.connect(self.changed) self.baseColorsWidget.changed.connect(self.baseColorsChanged) self.customAttributesWidget.changed.connect(self.customAttributesChanged) self.fontChooser.currentFontChanged.connect(self.fontChanged) self.fontSize.valueChanged.connect(self.fontChanged) self.printScheme.clicked.connect(self.printSchemeChanged) app.translateUI(self)
def __init__(self, parent, editable=False, spacerItemMove=False): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("ComboBoxPanel" + str(len(parent.findChildren(ComboBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) self.comboBox = QComboBox(self.frameBoxPanel) self.comboBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.comboBox.setFont(font) self.comboBox.setObjectName(self.objectName() + "_comboBox") self.comboBox.setMinimumWidth(70) # self.comboBox.setMaximumWidth(70) # self.hLayoutframeBoxPanel.addWidget(self.lineEdit) self.hLayoutframeBoxPanel.addWidget(self.comboBox) self.imageButton = QToolButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) if not spacerItemMove: spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.comboBox.currentIndexChanged.connect(self.comboBoxChanged) # self.comboBox.editTextChanged.connect(self.comboBoxEditTextChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.captionUnits = "" self.hasObject = False self.objectList = [] if editable == True: self.lineEdit = QLineEdit(self.frameBoxPanel) self.lineEdit.setObjectName("lineEdit") self.hLayoutframeBoxPanel.insertWidget(1, self.lineEdit) self.comboBox.setLineEdit(self.lineEdit) self.lineEdit.returnPressed.connect(self.comboBoxEditTextChanged)
class ProjectTreeColumn(QDialog): def __init__(self, parent=None): super(ProjectTreeColumn, self).__init__(parent, Qt.WindowStaysOnTopHint) self._layout = QVBoxLayout() self._layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(0) self.setLayout(self._layout) self._vbox = QVBoxLayout() self._vbox.setContentsMargins(0, 0, 0, 0) self._vbox.setSpacing(0) self._vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint) self._buttons = [] self._projects_area = QWidget() logger.debug("This is the projects area") logger.debug(self._projects_area) self._projects_area.setLayout(self._vbox) self._scroll_area = QScrollArea() self.layout().addWidget(self._scroll_area) self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self._scroll_area.setWidgetResizable(True) self._scroll_area.setEnabled(True) self._scroll_area.setWidget(self._projects_area) self._scroll_area.setGeometry(self.geometry()) self._vbox.setGeometry(self.geometry()) self.projects = [] self._active_project = None connections = ({ 'target': 'main_container', 'signal_name': 'addToProject(QString)', 'slot': self._add_file_to_project }, ) IDE.register_service('projects_explorer', self) IDE.register_signals('projects_explorer', connections) ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self) #FIXME: Should have a ninja settings object that stores tree state #FIXME: Or bettter, application data object #TODO: check this: #self.connect(ide, SIGNAL("goingDown()"), #self.tree_projects.shutdown) #def close_project_signal(): #self.emit(SIGNAL("updateLocator()")) def install_tab(self): ide = IDE.get_service('ide') ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide) self.connect(ide, SIGNAL("goingDown()"), self.close) def load_session_projects(self, projects): for project in projects: self._open_project_folder(project) def open_project_folder(self, folderName=None): if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") if folderName is None: folderName = QFileDialog.getExistingDirectory( self, self.tr("Open Project Directory"), directory) logger.debug("Choosing Foldername") if folderName: logger.debug("Opening %s" % folderName) self._open_project_folder(folderName) def _open_project_folder(self, folderName): ninjaide = IDE.get_service("ide") project = NProject(folderName) qfsm = ninjaide.filesystem.open_project(project) if qfsm: self.add_project(project) self.emit(SIGNAL("updateLocator()")) self.save_recent_projects(folderName) main_container = IDE.get_service('main_container') if main_container: main_container.show_editor_area() def _add_file_to_project(self, path): """Add the file for 'path' in the project the user choose here.""" if self._active_project: pathProject = [self._active_project.project] addToProject = add_to_project.AddToProject(pathProject, self) addToProject.exec_() if not addToProject.pathSelected: return main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if not editorWidget.file_path: name = QInputDialog.getText(None, self.tr("Add File To Project"), self.tr("File Name:"))[0] if not name: QMessageBox.information( self, self.tr("Invalid Name"), self.tr("The file name is empty, please enter a name")) return else: name = file_manager.get_basename(editorWidget.file_path) new_path = file_manager.create_path(addToProject.pathSelected, name) ide_srv = IDE.get_service("ide") old_file = ide_srv.get_or_create_nfile(path) new_file = old_file.save(editorWidget.get_text(), new_path) #FIXME: Make this file replace the original in the open tab else: pass # Message about no project @property def children(self): return self._projects_area.layout().count() def add_project(self, project): if project not in self.projects: ptree = TreeProjectsWidget(project) ptree.setParent(self) self.connect(ptree, SIGNAL("setActiveProject(PyQt_PyObject)"), self._set_active_project) self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"), self._close_project) pmodel = project.model ptree.setModel(pmodel) ptree.header().title = project.name ptree.header().path = project.path pindex = pmodel.index(pmodel.rootPath()) ptree.setRootIndex(pindex) #self._widget.layout().addWidget(scrollable_wrapper(ptree)) self._projects_area.layout().addWidget(ptree) if self._active_project is None: ptree.set_default_project() self.projects.append(ptree) ptree.setGeometry(self.geometry()) def _close_project(self, widget): """Close the project related to the tree widget.""" self.projects.remove(widget) if self._active_project == widget and len(self.projects) > 0: self.projects[0].set_default_project() self._layout.removeWidget(widget) ninjaide = IDE.get_service('ide') ninjaide.filesystem.close_project(widget.project.path) widget.deleteLater() def _set_active_project(self, tree_proj): if self._active_project is not None: self._active_project.set_default_project(False) self._active_project = tree_proj def close_opened_projects(self): for project in reversed(self.projects): self._close_project(project) def save_project(self): """Save all the opened files that belongs to the actual project.""" if self._active_project: path = self._active_project.project.path main_container = IDE.get_service('main_container') if path and main_container: main_container.save_project(path) def create_new_project(self): wizard = wizard_new_project.WizardNewProject(self) wizard.show() @property def current_project(self): if self._active_project: return self._active_project.project @property def current_tree(self): return self._active_project def save_recent_projects(self, folder): settings = IDE.data_settings() recent_project_list = settings.value('recentProjects', {}) #if already exist on the list update the date time projectProperties = json_manager.read_ninja_project(folder) name = projectProperties.get('name', '') description = projectProperties.get('description', '') if name == '': name = file_manager.get_basename(folder) if description == '': description = self.tr('no description available') if folder in recent_project_list: properties = recent_project_list[folder] properties["lastopen"] = QDateTime.currentDateTime() properties["name"] = name properties["description"] = description recent_project_list[folder] = properties else: recent_project_list[folder] = { "name": name, "description": description, "isFavorite": False, "lastopen": QDateTime.currentDateTime() } #if the length of the project list it's high that 10 then delete #the most old #TODO: add the length of available projects to setting if len(recent_project_list) > 10: del recent_project_list[self.find_most_old_open( recent_project_list)] settings.setValue('recentProjects', recent_project_list) def find_most_old_open(self, recent_project_list): listFounder = [] for recent_project_path, content in list(recent_project_list.items()): listFounder.append( (recent_project_path, int(content["lastopen"].toString("yyyyMMddHHmmzzz")))) listFounder = sorted(listFounder, key=lambda date: listFounder[1], reverse=True) # sort by date last used return listFounder[0][0] def closeEvent(self, event): self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self) event.ignore()
def init_UI(self): """Create all of the widget objects required""" layout = QVBoxLayout() self.setLayout(layout) # place scroll bars if the contents of the window are too large scroll = QScrollArea(self) layout.addWidget(scroll) scroll_content = QWidget(scroll) scroll.setWidgetResizable(True) scroll.setFixedHeight(800) self.grid = QGridLayout() scroll_content.setLayout(self.grid) #### validators for user input #### double_validator = QDoubleValidator() # floats int_validator = QIntValidator(0, 10000000) # positive integers msr_validator = QIntValidator(-1, 1000000) # integers >= -1 nat_validator = QIntValidator(1, 10000000) # natural numbers col_validator = QIntValidator(1, self.ncols - 1) # for number of columns #### table dimensions and ordering #### # choose the number of rows = number of multirun steps labels = ['# Omit', '# in Histogram', '# Columns', '# Rows'] default = ['5', '100', str(self.ncols), str(self.nrows)] vldtr = [int_validator, nat_validator, nat_validator, nat_validator] self.omit_edit, self.nhist_edit, self.cols_edit, self.rows_edit = [ self.make_label_edit(labels[i], self.grid, [0, 2 * i, 1, 1], default[i], vldtr[i])[1] for i in range(4) ] self.cols_edit.textChanged[str].connect(self.change_array_size) self.rows_edit.textChanged[str].connect(self.change_array_size) self.omit_edit.editingFinished.connect(self.update_repeats) self.nhist_edit.editingFinished.connect(self.update_repeats) # choose the order self.order_edit = QComboBox(self) self.order_edit.addItems( ['ascending', 'descending', 'random', 'coarse random', 'unsorted']) self.grid.addWidget(self.order_edit, 0, 8, 1, 1) #### create multirun list of values #### # metadata for the multirun list: which channels and timesteps self.measures = OrderedDict() labels = ['Variable label', 'measure', 'measure_prefix', '1st hist ID'] defaults = ['Variable 0', '0', 'Measure0', '0'] for i in range(len(labels)): label = QLabel(labels[i], self) self.grid.addWidget(label, i + 1, 0, 1, 1) self.measures[labels[i]] = QLineEdit(defaults[i], self) self.measures[labels[i]].textChanged.connect(self.update_all_stats) self.grid.addWidget(self.measures[labels[i]], i + 1, 1, 1, 3) self.measures['measure'].setValidator(int_validator) self.measures['1st hist ID'].setValidator(msr_validator) label.setText('1st ID (-1 to append)') # change label self.chan_choices = OrderedDict() labels = [ 'Type', 'Time step name', 'Analogue type', 'Analogue channel' ] sht = self.tr.get_esc()[2][2:] # 'Sequence header top' options = [ [ 'Time step length', 'Analogue voltage', 'GPIB', 'AWG1 chan : seg', 'AWG2 chan : seg', 'DDS1 port : profile', 'DDS2 module : profile', 'SLM holograms', 'Other' ], list( map(str.__add__, [str(i) for i in range(len(sht))], [': ' + hc[6][1].text for hc in sht])), # time step names ['Fast analogue', 'Slow analogue'], self.get_anlg_chans('Fast') ] positions = [[1, 4, 3, 2], [1, 6, 6, 1], [1, 7, 3, 1], [1, 8, 6, 1]] widgets = [QComboBox, QListWidget] for i in range(0, len(labels)): self.chan_choices[labels[i]] = widgets[i % 2]() if i % 2: self.chan_choices[labels[i]].setSelectionMode(3) self.chan_choices[labels[i]].addItems(options[i]) self.grid.addWidget(self.chan_choices[labels[i]], *positions[i]) self.chan_choices['Type'].currentTextChanged[str].connect( self.change_mr_type) self.chan_choices['Analogue type'].currentTextChanged[str].connect( self.change_mr_anlg_type) self.chan_choices['Analogue channel'].setEnabled(False) # enter desired time step selection via python cmd self.index_slice = QLineEdit('range(0,1,2)', self) self.grid.addWidget(self.index_slice, 3, 4, 3, 2) self.apply_slice_btn = QPushButton('Apply range', self) self.grid.addWidget(self.apply_slice_btn, 4, 4, 3, 2) self.apply_slice_btn.clicked.connect(self.apply_slice) # AWG takes a list for some arguments, so needs an index label = QLabel('List index:', self) self.grid.addWidget(label, 3, 7, 3, 1) self.list_index = QLineEdit('0', self) self.grid.addWidget(self.list_index, 4, 7, 3, 1) self.list_index.setValidator(int_validator) self.list_index.textEdited[str].connect(self.save_chan_selection) # add a new list of multirun values to the array self.col_index = self.make_label_edit('column index:', self.grid, position=[5, 0, 1, 1], default_text='0', validator=col_validator)[1] self.col_range = QLineEdit('np.linspace(0,1,%s)' % (self.nrows), self) self.grid.addWidget(self.col_range, 5, 2, 1, 2) # show the previously selected channels for this column: self.chan_choices['Time step name'].itemClicked.connect( self.save_chan_selection) self.chan_choices['Analogue channel'].itemClicked.connect( self.save_chan_selection) self.col_range.editingFinished.connect(self.save_chan_selection) self.col_index.textChanged[str].connect(self.set_chan_listbox) # add the column to the multirun values array add_var_button = QPushButton('Add column', self) add_var_button.clicked.connect(self.add_column_to_array) add_var_button.resize(add_var_button.sizeHint()) self.grid.addWidget(add_var_button, 6, 0, 1, 1) # clear the current list of user variables clear_vars_button = QPushButton('Clear', self) clear_vars_button.clicked.connect(self.clear_array) clear_vars_button.resize(clear_vars_button.sizeHint()) self.grid.addWidget(clear_vars_button, 6, 1, 1, 1) # suggest new measure when multirun started self.suggest_button = QPushButton('Auto-increment measure', self, checkable=True, checked=True) self.suggest_button.resize(self.suggest_button.sizeHint()) self.grid.addWidget(self.suggest_button, 6, 2, 1, 2) # choose last time step for multirun lts_label = QLabel('Last time step: ', self) self.grid.addWidget(lts_label, 7, 0, 1, 1) self.last_step_run_edit = self.make_label_edit('Running: ', self.grid, position=[7, 1, 1, 3])[1] self.last_step_run_edit.setText(self.ui_param['Last time step run']) self.last_step_run_edit.textChanged[str].connect(self.update_last_step) self.last_step_end_edit = self.make_label_edit('End: ', self.grid, position=[7, 5, 1, 3])[1] self.last_step_end_edit.setText(self.ui_param['Last time step end']) self.last_step_end_edit.textChanged[str].connect(self.update_last_step) # display current progress multirun_progress = QLabel( 'User variable: , omit 0 of 0 files, 0 of 100 histogram files, 0% complete' ) self.grid.addWidget(multirun_progress, 8, 0, 1, 12) reset_slot(self.progress, multirun_progress.setText, True) # table stores multirun values: self.table = QTableWidget(self.nrows, self.ncols) self.reset_array() self.grid.addWidget(self.table, 9, 0, 20, 12) scroll.setWidget(scroll_content)
def __init__(self,parent=None): QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) """ Set GUI to track mouse """ QWidget.setMouseTracking(self,True) """ Dynamixel bus TODO: add other motors here as needed with their correct address""" self.dxlbus = DXL_BUS(DEVICENAME, BAUDRATE) port_num = self.dxlbus.port() """ 467TODO: Based on motors we are using, modify ports and definition of rexarm Assume only use shld, elbw, wrst for now """ base = DXL_MX(port_num, 1) shld = DXL_MX(port_num, 2) elbw = DXL_MX(port_num, 3) wrst = DXL_AX(port_num, 4) #wrst2 = DXL_AX(port_num, 1) """Objects Using Other Classes""" self.kinect = None #Kinect() #self.rexarm = Rexarm((base,shld,elbw,wrst,wrst2),0) self.rexarm = Rexarm((base,shld,elbw, wrst),0) self.tp = TrajectoryPlanner(self.rexarm) self.sm = StateMachine(self.rexarm, self.tp, self.kinect) """ Attach Functions to Buttons & Sliders TODO: NAME AND CONNECT BUTTONS AS NEEDED """ self.ui.btn_estop.clicked.connect(self.estop) self.ui.btnUser1.setText("Calibrate") self.ui.btnUser1.clicked.connect(partial(self.sm.set_next_state, "calibrate")) self.ui.sldrBase.valueChanged.connect(self.sliderChange) self.ui.sldrShoulder.valueChanged.connect(self.sliderChange) self.ui.sldrElbow.valueChanged.connect(self.sliderChange) self.ui.sldrWrist.valueChanged.connect(self.sliderChange) self.ui.sldrWrist2.valueChanged.connect(self.sliderChange) self.ui.sldrMaxTorque.valueChanged.connect(self.sliderChange) self.ui.sldrSpeed.valueChanged.connect(self.sliderChange) self.ui.chk_directcontrol.stateChanged.connect(self.directControlChk) self.ui.rdoutStatus.setText("Waiting for input") """initalize manual control off""" self.ui.SliderFrame.setEnabled(False) """initalize rexarm""" self.rexarm.initialize() """Setup Threads""" # self.videoThread = VideoThread(self.kinect) # self.videoThread.updateFrame.connect(self.setImage) # self.videoThread.start() self.logicThread = LogicThread(self.sm) self.logicThread.start() self.displayThread = DisplayThread(self.rexarm, self.sm) self.displayThread.updateJointReadout.connect(self.updateJointReadout) self.displayThread.updateEndEffectorReadout.connect(self.updateEndEffectorReadout) self.displayThread.updateStatusMessage.connect(self.updateStatusMessage) self.displayThread.start() """ Setup Timer this runs the trackMouse function every 50ms """ self._timer = QTimer(self) self._timer.timeout.connect(self.trackMouse) self._timer.start(50)