def __init__(self, db, dbName, tableName): QtGui.QTabWidget.__init__(self) self.db = db self.dbName = dbName self.tableName = tableName self.setupUi(self) self.txtLimit.setValue(self.defaultLimit) self.lblQueryDesc.setText("SELECT * FROM %s WHERE" % self.db.quoteIdentifier(self.tableName)) QObject.connect(self.txtWhere, SIGNAL("returnPressed()"), self.refreshData) self.db.setDatabase(self.dbName) #Retrieve self.refreshInfo() self.refreshStructure() self.refreshIndexes() #Data self.tableModel = QPyTableModel(self, self.db) self.tableModel.setTable(self.tableName) self.tableData.setModel(self.tableModel) self.refreshData()
def __init__(self,username,containerItem = None,parent = None): QObject.__init__(self,parent) HashableMixin.__init__(self) self._username = username self._contentItems = [] self._authorizer = Authorizer(self._username) self._containerItem = containerItem
def __init__(self, data, parent=None): QObject.__init__(self, parent) self.populated = False self.itemData = data self.childItems = [] if parent: parent.appendChild(self)
def __init__(self, hazard_layer, exposure_layer, function): """Constructor for the impact calculator thread. :param hazard_layer: read_layer object containing the Hazard. data. :type hazard_layer: read_layer :param exposure_layer: read_layer object containing the Exposure data. :type exposure_layer: read_layer :param function: Function that defines how the Hazard assessment will be computed. :type function: FunctionProvider :raises: InsufficientParametersError if not all parameters are set. """ threading.Thread.__init__(self) QObject.__init__(self) self._hazardLayer = hazard_layer self._exposureLayer = exposure_layer self._function = function self._impactLayer = None self._result = None self._exception = None self._traceback = None
def __init__(self, widget): QObject.__init__(self) self.parent = widget self.ser = serial.Serial() self.mutex = QtCore.QMutex(mode=QtCore.QMutex.Recursive) self.moveThread = thread.WorkerThread() self.moveThread.canDropJobs = True
def __init__(self, navigationInterpreter, positionModel, editor): QObject.__init__(self) self.baseInterpret = navigationInterpreter self.posModel = positionModel self.rubberBand = QRubberBand(QRubberBand.Rectangle, editor) self.origin = QPoint() self.originpos = object()
def __init__(self, source_node, source_channel, sink_node, sink_channel, enabled=True, properties=None, parent=None): QObject.__init__(self, parent) self.source_node = source_node if isinstance(source_channel, six.string_types): source_channel = source_node.output_channel(source_channel) elif source_channel not in source_node.output_channels(): raise ValueError("%r not in in nodes output channels." \ % source_channel) self.source_channel = source_channel self.sink_node = sink_node if isinstance(sink_channel, six.string_types): sink_channel = sink_node.input_channel(sink_channel) elif sink_channel not in sink_node.input_channels(): raise ValueError("%r not in in nodes input channels." \ % source_channel) self.sink_channel = sink_channel if not compatible_channels(source_channel, sink_channel): raise IncompatibleChannelTypeError( "Cannot connect %r to %r" \ % (source_channel.type, sink_channel.type) ) self.__enabled = enabled self.__dynamic_enabled = False self.__tool_tip = "" self.properties = properties or {}
def __init__(self, parent = None): """ Constructor @param parent reference to the parent object (QObject) """ QObject.__init__(self, parent)
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, destdir, persist_limit, **kwargs): QObject.__init__(self) persist_limit = PersistLimit(persist_limit) BuildDownloadManager.__init__(self, destdir, session=get_http_session(), persist_limit=persist_limit, **kwargs)
def __init__(self): QObject.__init__(self) TestRunner.__init__(self) self.verdict = None self.launcher = None self.launcher_kwargs = {} self.run_error = False
def __init__(self, navigationInterpreter, positionModel, BoxContr, widget): ''' Class which interacts directly with the image scene :param navigationInterpreter: :param positionModel: :param BoxContr: :param widget: The main widget ''' QObject.__init__(self) self.baseInterpret = navigationInterpreter self._posModel = positionModel self.rubberBand = RedRubberBand(QRubberBand.Rectangle, widget) self.boxController=BoxContr self.leftClickReleased.connect(BoxContr.addNewBox) self.rightClickReceived.connect(BoxContr.onChangedPos) #self.deleteSelectedItemsSignal.connect(BoxContr.deleteSelectedItems) self.origin = QPoint() self.originpos = object()
def __init__(self,editor,connectionInput,boxListModel, delegateMethod=None): ''' Class which controls all boxes on the scene :param scene: :param connectionInput: The imput slot to which connect all the new boxes :param boxListModel: ''' scene = editor.imageScenes[2] self._editor = editor QObject.__init__(self,parent=scene.parent()) self._setUpRandomColors() self.scene=scene self.connectionInput=connectionInput self._currentBoxesList=[] #self._currentActiveItem=[] #self.counter=1000 self.currentColor=self._getNextBoxColor() self.boxListModel=boxListModel self.scene.selectionChanged.connect(self.handleSelectionChange) boxListModel.boxRemoved.connect(self.deleteItem) boxListModel.signalSaveAllBoxesToCSV.connect(self.saveBoxesToCSV) self.delegateMethod = delegateMethod
def __init__(self, x, y, filename, mythDB, startAtEnd = False): QObject.__init__(self) self.filename = filename self.mythDB = mythDB self.startAtEnd = startAtEnd self.ended = False self.lastPosition = 0 self.emitFinished = True self.currentChannel = None self.previousChannel = None self.guide = None self.commskip = True self.getSkipList() self.bookmark = self.mythDB.bookmark(self.filename) self.program = self.mythDB.getProgram(self.filename) self.recording = self.mythDB.programInUse(self.program) self.videoOutput = VideoOutput(None, self.keyPressHandler) self.createOverlays() self.videoOutput.readyForOverlay.connect(self.placeOverlays) self.videoOutput.move(x, y) self.videoOutput.showFullScreen() self.startBackend()
def __init__(self, gelement, parent=None): QObject.__init__(self, parent) self._gelement = gelement self._gelement.get_bus().add_signal_watch() self._gelement.get_bus().connect('message', self.cb_bus) if GObjectLoop._instance is None: GObjectLoop()
def __init__( self, tiling, stackedImageSources, cache_size=100, request_queue_size=100000, n_threads=2, layerIdChange_means_dirty=False, parent=None ): QObject.__init__( self, parent = parent ) self.tiling = tiling self.axesSwapped = False self._sims = stackedImageSources self._cache_size = cache_size self._request_queue_size = request_queue_size self._n_threads = n_threads self._layerIdChange_means_dirty = layerIdChange_means_dirty self._current_stack_id = self._sims.stackId self._cache = _TilesCache(self._current_stack_id, self._sims, maxstacks=self._cache_size) self._sims.layerDirty.connect(self._onLayerDirty) self._sims.visibleChanged.connect(self._onVisibleChanged) self._sims.opacityChanged.connect(self._onOpacityChanged) self._sims.sizeChanged.connect(self._onSizeChanged) self._sims.orderChanged.connect(self._onOrderChanged) self._sims.stackIdChanged.connect(self._onStackIdChanged) if self._layerIdChange_means_dirty: self._sims.layerIdChanged.connect(self._onLayerIdChanged) self._keepRendering = True
def __init__(self, parent=None): QFrame.__init__(self, parent) self.setAutoFillBackground(True) self.palette().setColor(self.backgroundRole(), spec.POV_COLOR) self.benderButtons = bender.Buttons(self) self.bender = bender.Bender(self) self.bender.setValue(150) self.wheelPad = pk.widgets.WheelPad(self) self.history = History(self.bender, parent=self) self.history.setMinimumHeight(50) QObject.connect(self.benderButtons, SIGNAL('bendUp()'), self.bender.bendUp) QObject.connect(self.benderButtons, SIGNAL('bendDown()'), self.bender.bendDown) QObject.connect(self.benderButtons, SIGNAL('bendBack()'), self.bender.bendBack) QObject.connect(self.bender, SIGNAL('valueChanged(float)'), self.emitTempo) QObject.connect(self.wheelPad, SIGNAL('moved_y(int)'), self.slotWheel) Layout = QVBoxLayout(self) Layout.setMargin(0) Layout.addWidget(self.history) Layout.addWidget(self.benderButtons) Layout.setStretchFactor(self.benderButtons, 0) Layout.addWidget(self.wheelPad) Layout.setStretchFactor(self.wheelPad, 1)
def initGui(self): # Actions self.action_convert = QAction(QIcon(path.join(_current_path, 'convert.png')), QCoreApplication.translate('RuGeocoder', 'Convert CSV to SHP'), self.iface.mainWindow()) QObject.connect(self.action_convert, SIGNAL("triggered()"), self.run_convert) self.action_batch_geocoding = QAction(QIcon(path.join(_current_path, 'icon.png')), QCoreApplication.translate('RuGeocoder', 'Batch geocoding'), self.iface.mainWindow()) QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch) self.action_quick_geocoding = self.__quick_tlb.toggleViewAction() self.action_quick_geocoding.setIcon(QIcon(path.join(_current_path, 'edit-find-project.png'))) self.action_quick_geocoding.setText(QCoreApplication.translate('RuGeocoder', '&Quick geocoding toolbox')) # Add toolbar button and menu item self.toolbar.addAction(self.action_convert) self.iface.addPluginToWebMenu(self.menu_name, self.action_convert) self.toolbar.addAction(self.action_batch_geocoding) self.iface.addPluginToWebMenu(self.menu_name, self.action_batch_geocoding) self.toolbar.addSeparator() self.toolbar.addAction(self.action_quick_geocoding) self.iface.addPluginToWebMenu(self.menu_name, self.action_quick_geocoding)
def __init__(self, features, uid, errors): QObject.__init__(self) self.features = features self.last_fid = features[-1][0] self.errors = errors self.uid = uid self.vertices_occur = {} self.edges_occur = {} self.f_dict = {} self.self_loops = [] for i in self.features: self.f_dict[i[0]] = [i[1], i[2]] for vertex in vertices_from_wkt_2(i[2]): break first = vertex for vertex in vertices_from_wkt_2(i[2]): pass last = vertex try: self.vertices_occur[first] += [i[0]] except KeyError, e: self.vertices_occur[first] = [i[0]] try: self.vertices_occur[last] += [i[0]] except KeyError, e: self.vertices_occur[last] = [i[0]]
def replaceVariable(self, pendingVar, newVar): """ replace existing variable in list with new one @param pendingVar: var to replace @param newVar: new var""" vwOld = self.variableList.getVariableWrapper(pendingVar) vwNew = self.variableList.replaceVar(pendingVar, newVar) QObject.connect(vwNew, SIGNAL('replace(PyQt_PyObject, PyQt_PyObject)'), self.replaceVariable)
def __init__(self, parent=None, name=None, *args, **kwargs): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param name: Component name. :type name: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) QObject.__init__(self, parent, *args, **kwargs) # --- Setting class attributes. --- self.__name = None self.name = name self.__activated = False self.__initialized = False self.__deactivatable = True
def __init__( self, osm_file, layers=OSM_LAYERS, white_list_column=WHITE_LIST, delete_empty_layers=False, load_only=False, osm_conf=None): self.__osmFile = osm_file self.__layers = layers if not white_list_column: white_list_column = { 'multilinestrings': None, 'points': None, 'lines': None, 'multipolygons': None} self.__whiteListColumn = white_list_column self.__deleteEmptyLayers = delete_empty_layers self.__loadOnly = load_only # If an osm_conf is provided ? if not osm_conf: current_dir = dirname(realpath(__file__)) self._osm_conf = join(current_dir, 'QuickOSMconf.ini') else: self._osm_conf = osm_conf.encode("utf-8") QObject.__init__(self)
def __init__(self, weboob, parent=None): QObject.__init__(self, parent) self.weboob = weboob self.weboob.callbacks['login'] = self.callback(self.LoginRequest) self.mutex = QMutex() self.requests = [] self.connect(self, SIGNAL('new_request'), self.do_request)
def __init__(self): QObject.__init__(self) self._action = core.actionManager().addAction("mSettings/aSettings", _tr( "Settings.."), QIcon(':/enkiicons/settings.png')) self._action.setStatusTip(_tr( "Edit settigns..")) self._action.triggered.connect(self._onEditSettings)
def __init__(self, parent = None): QObject.__init__(self, parent) self.jinja = Environment(loader = FileSystemLoader("data/templates"), autoescape = True) self.jinja.filters["likes"] = filter_likes self.jinja.filters["twitterise"] = filter_twitterise self.jinja.filters["timesince"] = filter_timesince self.mapper = Mapper() self.mapper.connect("/", controller = "LolViews", action = "feed") self.mapper.connect("/login", controller = "LolViews", action = "login") self.mapper.connect("/user/:user", controller = "LolViews", action = "feed") self.notes = NotificationServer() from PyQt4.QtCore import QSettings settings = QSettings() if settings.contains("session"): from cPickle import loads self.session = loads(str(settings.value("session").toString())) else: self.session = Session() self.ff = FriendFeedAPI(self.session) self.deferredResponses = set()
def __init__(self): """Constructor for the KeywordIO object.""" QObject.__init__(self) # path to sqlite db path self.keyword_db_path = None self.setup_keyword_db_path() self.connection = None
def itemCollapsedOrExpanded(self, item): if item.isExpanded(): item.expanded() else: # collapsed item.collapsed() self.setVisibleRowCount() QObject.emit(self, SIGNAL("contentChanged(void)"))
def __init__(self, theHazardLayer, theExposureLayer, theFunction): """Constructor for the impact calculator thread. Args: * Hazard layer: InaSAFE read_layer object containing the Hazard data. * Exposure layer: InaSAFE read_layer object containing the Exposure data. * Function: a InaSAFE function that defines how the Hazard assessment will be computed. Returns: None Raises: InsufficientParametersException if not all parameters are set. Requires three parameters to be set before execution can take place: """ threading.Thread.__init__(self) QObject.__init__(self) self._hazardLayer = theHazardLayer self._exposureLayer = theExposureLayer self._function = theFunction self._impactLayer = None self._result = None self._exception = None self._traceback = None
def __init__(self, distributedObjects): """ init tracepoint controller and members. @param distributedObjects: passing distributed objects @note There are following signals: \n * insertDockWidgets() : necessary for plugin system\n * clicked(QModelIndex): if a row in tracepointView is clicked\n * cleanupModels(): clear Tracepoints\n * runClicked((): clear Tracepoint Data on every click on run button\n """ QObject.__init__(self) self.distributedObjects = distributedObjects """@var self._model: (TracepointModel), this class provides the model for tracepointView""" self._model = TracepointModel(self.distributedObjects) """@var self.tracepointView: (TracepointView), this class presents data from _model""" self.tracepointView = TracepointView() self.tracepointView.tracepointView.setModel(self._model) #register with session manager to save Tracepoints self.distributedObjects.signalProxy.emitRegisterWithSessionManager(self, "Tracepoints") self.distributedObjects.signalProxy.insertDockWidgets.connect(self.insertDockWidgets) self.tracepointView.tracepointView.clicked.connect(self.updateWaveforms) self.distributedObjects.signalProxy.inferiorStoppedNormally.connect(self.updateWaveforms) self.distributedObjects.signalProxy.cleanupModels.connect(self._model.clearTracepoints) self.distributedObjects.signalProxy.runClicked.connect(self._model.clearTracepointData)
def addVar(self, variableToTrace): """ add a var to trace its value @param variableToTrace: variable name of the variable that shoudl be traced""" vw = self.variableList.addVarByName(variableToTrace) QObject.connect(vw, SIGNAL('replace(PyQt_PyObject, PyQt_PyObject)'), self.replaceVariable) newValueList = ValueList(variableToTrace, vw.getType()) self.wave.append(newValueList)
# -*- coding: utf-8 -*- # Creation of a PDF tree from gedcom and options import os.path from reportlab.lib.units import mm from reportlab.lib.pagesizes import A4 from lab.abstractLab import * from PyQt4.QtCore import QSettings, QObject, QString qo = QObject() tr = qo.tr class Tree: def __init__(self, gedcom): self.gedcom = gedcom self.options = QSettings("A3X", "pySequoia") self.max_generations = self.options.value("max_generations").toInt()[0] self.notes = [] self.counter = 0 def setProgressDialog(self, dialog): """Gives a ProgressDialog for displaying progression""" self.progressDialog = dialog def setProgression(self, progress): if hasattr(self, 'progressDialog'): self.progressDialog.setValue(progress)
def __init__(self): QObject.__init__(self)
def __init__(self): QObject.__init__(self) self.load()
def name(cls): return QObject.tr(translator, 'Export to FTP site')
def name(cls): return QObject.tr(translator, 'Export to folder')
# # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import os from datetime import datetime import ftplib from qgis.core import (QgsProject) from PyQt4.QtCore import (QObject) from PyQt4.QtGui import (QFileDialog, QInputDialog, QDialog, QLineEdit) from utils import (tempFolder) from ui_ftp_configuration import Ui_FtpConfiguration translator = QObject() class Exporter(QObject): """ Generic base class for web map exporters """ def __init__(self): super(QObject, self).__init__() @classmethod def type(cls): """ :return: Unique string for exporter type """ return ''
def __init__(self, composerView, iface): QObject.__init__(self, composerView) self._compView = composerView self._stdmTB = self.mainWindow().addToolBar("STDM Document Designer") self._selectMoveAction = None self._iface = iface #Container for custom editor widgets self._widgetMappings = {} #Hide default dock widgets if self.itemDock() is not None: self.itemDock().hide() if self.atlasDock() is not None: self.atlasDock().hide() if self.generalDock() is not None: self.generalDock().hide() # Remove default toolbars self._remove_composer_toolbar('mAtlasToolbar') self._remove_composer_toolbar('mComposerToolbar') #Create dock widget for configuring STDM data source self._stdmDataSourceDock = QDockWidget( QApplication.translate("ComposerWrapper", "STDM Data Source"), self.mainWindow()) self._stdmDataSourceDock.setObjectName("STDMDataSourceDock") self._stdmDataSourceDock.setMinimumWidth(300) self._stdmDataSourceDock.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetClosable) self.mainWindow().addDockWidget(Qt.RightDockWidgetArea, self._stdmDataSourceDock) self._dataSourceWidget = ComposerDataSourceSelector() self._stdmDataSourceDock.setWidget(self._dataSourceWidget) self._stdmDataSourceDock.show() #Re-insert dock widgets if self.generalDock() is not None: self.generalDock().show() if self.itemDock() is not None: self.itemDock().show() #Create dock widget for configuring STDM item properties self._stdmItemPropDock = QDockWidget( QApplication.translate("ComposerWrapper", "STDM item properties"), self.mainWindow()) self._stdmItemPropDock.setObjectName("STDMItemDock") self._stdmItemPropDock.setMinimumWidth(300) self._stdmItemPropDock.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetClosable) self.mainWindow().addDockWidget(Qt.RightDockWidgetArea, self._stdmItemPropDock) self._stdmItemPropDock.show() #Re-arrange dock widgets and push up STDM data source dock widget if self.generalDock() is not None: self.mainWindow().splitDockWidget(self._stdmDataSourceDock, self.generalDock(), Qt.Vertical) if self.itemDock() is not None: self.mainWindow().splitDockWidget(self._stdmDataSourceDock, self.itemDock(), Qt.Vertical) if self.generalDock() is not None: self.mainWindow().tabifyDockWidget(self.generalDock(), self.itemDock()) if self.itemDock() is not None: self.mainWindow().splitDockWidget(self.itemDock(), self._stdmItemPropDock, Qt.Vertical) #Set focus on composition properties window if self.generalDock() is not None: self.generalDock().activateWindow() self.generalDock().raise_() #Connect signals self.composition().itemRemoved.connect(self._onItemRemoved) self._dataSourceWidget.cboDataSource.currentIndexChanged.connect( self.propagateDataSourceSelection) self.composerView().selectedItemChanged.connect(self._onItemSelected) #Current template document file self._currDocFile = None #Copy of template document file self._copy_template_file = None self._selected_item_uuid = unicode() self._current_ref_table_index = -1
def customEvent(self, event): if event.type() == ExecuteCallEvent.ExecuteCall: self._execute() else: QObject.customEvent(self, event)
def __init__(self, parent): QObject.__init__(self, parent) self.selection = []
def __init__(self, future, parent=None): QObject.__init__(self, parent) self._future = future self._future._watchers.append(self._stateChanged)
def __init__(self, canvas): """Constructor :param canvas: """ QObject.__init__(self) self.canvas = canvas # Set up slots so we can mimic the behaviour of QGIS when layers # are added. # noinspection PyArgumentList QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers) # noinspection PyArgumentList QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer) # noinspection PyArgumentList QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers) # For processing module self.destCrs = None # For keeping track of which layer is active in the legend. self.active_layer = None # In the next section of code, we are going to do some monkey patching # to make the QGIS processing framework think that this mock QGIS IFACE # instance is the actual one. It will also ensure that the processing # algorithms are nicely loaded and available for use. # Since QGIS > 2.0, the module is moved from QGisLayers to dataobjects # pylint: disable=F0401, E0611 if QGis.QGIS_VERSION_INT > 20001: from processing.tools import dataobjects else: from processing.core import QGisLayers as dataobjects import processing from processing.core.Processing import Processing # pylint: enable=F0401, E0611 processing.classFactory(self) # We create our own getAlgorithm function below which will will monkey # patch in to the Processing class in QGIS in order to ensure that the # Processing.initialize() call is made before asking for an alg. @staticmethod def mock_getAlgorithm(name): """ Modified version of the original getAlgorithm function. :param name: Name of the algorithm to load. :type name: str :return: An algorithm concrete class. :rtype: QgsAlgorithm ? """ Processing.initialize() for provider in Processing.algs.values(): if name in provider: return provider[name] return None # Now we let the monkey loose! Processing.getAlgorithm = mock_getAlgorithm # We also need to make dataobjects think that this iface is 'the one' # Note. the placement here (after the getAlgorithm monkey patch above) # is significant, so don't move it! dataobjects.iface = self
def __init__(self, parent=None, function=None): QObject.__init__(self, parent) self.function = function self._future = Future()
def __init__(self): QObject.__init__(self) self.mRepositories = {} self.httpId = {} # {httpId : repoName} self.mInspectionFilter = None
def __init__(self, parent): QObject.__init__(self, parent) self.setObjectName("Menu") self.popup = QMenu(i18n("Scripter")) MenuHooks().insertMenuAfter("E&xtras", self.popup) self._load_entries()
def __init__(self, visaResource, parent=None): VisaInstrument.__init__(self, visaResource) QObject.__init__(self, parent)
def __init__(self): QObject.__init__(self) self.mPlugins = {} # the dict of plugins (dicts) self.repoCache = {} # the dict of lists of plugins (dicts) self.localCache = {} # the dict of plugins (dicts) self.obsoletePlugins = [] # the list of outdated 'user' plugins masking newer 'system' ones
def __init__(self, name='', parent=None): QObject.__init__(self, parent) self.setObjectName(name)
def __init__(self, key): QObject.__init__(self) self.key = key
def get_value(self): return self.password.text() if __name__ == '__main__': ''' Demo application showing PinMatrix widget in action ''' a = QApplication(sys.argv) matrix = PinMatrixWidget() def clicked(): print("PinMatrix value is", matrix.get_value()) print("Possible button combinations:", matrix.get_strength()) sys.exit() ok = QPushButton('OK') QObject.connect(ok, SIGNAL('clicked()'), clicked) vbox = QVBoxLayout() vbox.addWidget(matrix) vbox.addWidget(ok) w = QWidget() w.setLayout(vbox) w.move(100, 100) w.show() a.exec_()
def __init__(self, canvas): """Constructor :param canvas: """ QObject.__init__(self) self.canvas = canvas self.legend = QgisLegend(canvas) self.message_bar = QgsMessageBar(None) # Set up slots so we can mimic the behaviour of QGIS when layers # are added. LOGGER.debug('Initialising canvas...') # noinspection PyArgumentList QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers) # noinspection PyArgumentList QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer) # noinspection PyArgumentList QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers) # For processing module self.destCrs = None # For keeping track of which layer is active in the legend. self.active_layer = None # In the next section of code, we are going to do some monkey patching # to make the QGIS processing framework think that this mock QGIS IFACE # instance is the actual one. It will also ensure that the processing # algorithms are nicely loaded and available for use. # noinspection PyUnresolvedReferences from processing.tools import dataobjects # noinspection PyUnresolvedReferences import processing # noinspection PyUnresolvedReferences from processing.core.Processing import Processing # pylint: enable=F0401, E0611 processing.classFactory(self) # We create our own getAlgorithm function below which will will monkey # patch in to the Processing class in QGIS in order to ensure that the # Processing.initialize() call is made before asking for an alg. @staticmethod def mock_getAlgorithm(name): """ Modified version of the original getAlgorithm function. :param name: Name of the algorithm to load. :type name: str :return: An algorithm concrete class. :rtype: QgsAlgorithm ? """ Processing.initialize() # FIXME: Had some weird bug in QGIS 2.18 MacOSX (KyngChaos) try: providers = Processing.algs.values() except: providers = Processing.algs().values() for provider in providers: if name in provider: return provider[name] return None # Now we let the monkey loose! Processing.getAlgorithm = mock_getAlgorithm # We also need to make dataobjects think that this iface is 'the one' # Note. the placement here (after the getAlgorithm monkey patch above) # is significant, so don't move it! dataobjects.iface = self # set up a layer tree bridge so that new added layers appear in legend self.layer_tree_root = QgsProject.instance().layerTreeRoot() self.bridge = QgsLayerTreeMapCanvasBridge( self.layer_tree_root, self.canvas) self.bridge.setCanvasLayers()
def __init__(self, parent): """ Create a ThunkEventHandler that installs itself in the event loop for ``parent``. """ QObject.__init__(self, parent) parent.installEventFilter(self)
def __init__(self, password, encoded_value): super(PinButton, self).__init__('?') self.password = password self.encoded_value = encoded_value QObject.connect(self, SIGNAL('clicked()'), self._pressed)
def __init__(self): QObject.__init__(self) self._cancelling = False
def __init__(self, parent): QObject.__init__(self, parent) self.job_id = None self.__errors = {} self._warnings = []
def __draw__(self): global _progress, f f = open(filename, "a") f.write("Rendering function...\n") f.close() for i in range(len(Paths["Images"])): Visum.Graphic.Backgrounds.ItemByKey( Paths["Images"][i]).Draw = False if not os.path.exists(self._image_path) or Paths["Images"].count( self._image_path) == 0: f = open(filename, "a") f.write("If not os.path.exists or image not in Paths...\n") f.close() QObject.connect(self._webpage, SIGNAL("loadStarted()"), self.__loading__) QObject.connect(self._webpage, SIGNAL("loadProgress(int)"), self.__progress__) QObject.connect(self._webpage, SIGNAL("loadFinished(bool)"), self.__loaded__) self._webpage.mainFrame().load(QUrl(self._url)) self._webpage.mainFrame().evaluateJavaScript( "x0 = %f; y0 = %f; x1 = %f; y1 = %f;" % (self._param[0], self._param[1], self._param[2], self._param[3])) self._webpage.mainFrame().evaluateJavaScript( "width = %d; height = %d;" % (self._multiply * self._dimension[0], self._multiply * self._dimension[1])) self._webpage.mainFrame().evaluateJavaScript("value = %d;" % (self._layer)) while self._loading: QCoreApplication.processEvents() QObject.disconnect(self._webpage, SIGNAL("loadStarted()"), self.__loading__) QObject.disconnect(self._webpage, SIGNAL("loadProgress(int)"), self.__progress__) QObject.disconnect(self._webpage, SIGNAL("loadFinished(bool)"), self.__loaded__) loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) timerProgress = QTimer() QObject.connect(timerProgress, SIGNAL("timeout()"), self.__on_loop__) if self._layer == 10: timer.start(0) elif self._layer >= 4 and self._layer <= 9: timer.start(800 * self._multiply * 4.0) timerProgress.start(800 * self._multiply * 4.0 / 16.0) else: timer.start(2400 * self._multiply * 4.0) timerProgress.start(2400 * self._multiply * 4.0 / 49.0) loop.exec_() QObject.disconnect(timerProgress, SIGNAL("timeout()"), self.__on_loop__) background_params = self._webpage.mainFrame().evaluateJavaScript( "getRealBounds();").toString() background_params = background_params[1:-1] background_params = [ float(s) for s in background_params.split(", ") ] self._webpage.setViewportSize( self._webpage.mainFrame().contentsSize()) f = open(filename, "a") f.write("Setting up an image file...\n") f.close() image = QImage(self._webpage.viewportSize(), QImage.Format_RGB32) f = open(filename, "a") f.write("Starting a painter...\n") f.close() painter = QPainter(image) f = open(filename, "a") f.write("Rendering from frame...\n") f.write(str(self._webpage.viewportSize()) + "\n") f.close() self._webpage.mainFrame().render(painter) painter.end() image.save(self._image_path) f = open(filename, "a") f.write("Image saved.\n") f.close() Visum.Graphic.AddBackgroundOnPos(self._image_path, background_params[0], background_params[1], background_params[2], background_params[3]) Paths["Images"].append(self._image_path) f = open(filename, "a") f.write("End of if not os.path.exists or image not in Paths.\n") f.close() else: f = open(filename, "a") f.write("If os.path.exists and image in Paths...\n") f.close() index = Paths["Images"].index(self._image_path) Visum.Graphic.Backgrounds.ItemByKey( Paths["Images"][index]).Draw = True f = open(filename, "a") f.write("End of if os.path.exists and image in Paths...\n") f.close() _progress = 100 del self._webpage f = open(filename, "a") f.write("Rendering completed.\n") f.close()
def __init__(self, QObject_parent=None): QObject.__init__(self, QObject_parent)
def __init__(self, logger, opts, parent=None): MainWindow.__init__(self, opts, parent) Ui_MainWindow.__init__(self) self.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(__appname__ + _(' - LRF Viewer')) self.logger = logger self.opts = opts self.create_document() self.spin_box_action = self.spin_box = QSpinBox() self.tool_bar.addWidget(self.spin_box) self.tool_bar.addSeparator() self.slider_action = self.slider = QSlider(Qt.Horizontal) self.tool_bar.addWidget(self.slider) self.tool_bar.addSeparator() self.search = SearchBox2(self) self.search.initialize('lrf_viewer_search_history') self.search_action = self.tool_bar.addWidget(self.search) self.search.search.connect(self.find) self.action_next_page.setShortcuts( [QKeySequence.MoveToNextPage, QKeySequence(Qt.Key_Space)]) self.action_previous_page.setShortcuts( [QKeySequence.MoveToPreviousPage, QKeySequence(Qt.Key_Backspace)]) self.action_next_match.setShortcuts(QKeySequence.FindNext) self.addAction(self.action_next_match) QObject.connect(self.action_next_page, SIGNAL('triggered(bool)'), self.next) QObject.connect(self.action_previous_page, SIGNAL('triggered(bool)'), self.previous) QObject.connect(self.action_back, SIGNAL('triggered(bool)'), self.back) QObject.connect(self.action_forward, SIGNAL('triggered(bool)'), self.forward) QObject.connect(self.action_next_match, SIGNAL('triggered(bool)'), self.next_match) QObject.connect(self.action_open_ebook, SIGNAL('triggered(bool)'), self.open_ebook) QObject.connect(self.action_configure, SIGNAL('triggered(bool)'), self.configure) QObject.connect(self.spin_box, SIGNAL('valueChanged(int)'), self.go_to_page) QObject.connect(self.slider, SIGNAL('valueChanged(int)'), self.go_to_page) self.graphics_view.setRenderHint(QPainter.Antialiasing, True) self.graphics_view.setRenderHint(QPainter.TextAntialiasing, True) self.graphics_view.setRenderHint(QPainter.SmoothPixmapTransform, True) self.closed = False
def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close()
def create_document(self): self.document = Document(self.logger, self.opts) QObject.connect(self.document, SIGNAL('chapter_rendered(int)'), self.chapter_rendered) QObject.connect(self.document, SIGNAL('page_changed(PyQt_PyObject)'), self.page_changed)
def __init__(self, *args): QObject.__init__(self)