def _setupHelpActions(self): actionsgroup = QtWidgets.QActionGroup(self) # About icon = qtsupport.geticon('about.svg', __name__) QtWidgets.QAction( icon, self.tr('&About'), actionsgroup, objectName='aboutAction', toolTip=self.tr('Show program information'), statusTip=self.tr('Show program information'), triggered=lambda: self.aboutdialog.exec_()) # AboutQt icon = QtGui.QIcon(':/qt-project.org/qmessagebox/images/qtlogo-64.png') # @COMPATIBILITY: Qt4 --> Qt5 if not icon.availableSizes(): icon = QtGui.QIcon(':/trolltech/qmessagebox/images/qtlogo-64.png') if not icon.availableSizes(): icon = QtGui.QIcon.fromTheme('qtlogo-64') QtWidgets.QAction( icon, self.tr('About &Qt'), actionsgroup, objectName='aboutQtAction', toolTip=self.tr('Show information about Qt'), statusTip=self.tr('Show information about Qt'), triggered=lambda: QtWidgets.QMessageBox.aboutQt(self)) return actionsgroup
def openfile(self): self.scene.clear() self.graphicsview.setTransform(QtGui.QTransform()) filename = QtWidgets.QFileDialog.getOpenFileName() if filename: pixmap = QtGui.QPixmap(filename) item = self.scene.addPixmap(pixmap) self.scene.setSceneRect(item.boundingRect())
def _setupViewActions(self): style = self.style() actions = QtWidgets.QActionGroup(self) icon = style.standardIcon(QtWidgets.QStyle.SP_DialogResetButton) QtWidgets.QAction(icon, self.tr('Reset'), actions, objectName='resetAction', statusTip=self.tr('Reset'), triggered=self.onReset) QtWidgets.QAction(actions).setSeparator(True) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/zoom-in-32.png') QtWidgets.QAction(icon, self.tr('Zoom In'), actions, objectName='zoomInAction', statusTip=self.tr('Zoom In'), shortcut=self.tr('Ctrl++'), triggered=lambda: self.graphicsview.scale(1.2, 1.2)) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/zoom-out-32.png') QtWidgets.QAction( icon, self.tr('Zoom Out'), actions, objectName='zoomOutAction', statusTip=self.tr('Zoom Out'), shortcut=self.tr('Ctrl+-'), triggered=lambda: self.graphicsview.scale(1 / 1.2, 1 / 1.2)) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/page-setup-24.png') QtWidgets.QAction(icon, self.tr('Zoom 1:1'), actions, objectName='zoomResetAction', statusTip=self.tr('Zoom 1:1'), triggered=lambda: self.graphicsview.setTransform( QtGui.QTransform(1, 0, 0, -1, 0, 0))) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/fit-page-32.png') QtWidgets.QAction( icon, self.tr('Zoom Fit'), actions, objectName='zoomFitAction', statusTip=self.tr('Zoom Fit'), #checkable=True, triggered=lambda: self.graphicsview.fitInView( self.graphicsview.sceneRect(), QtCore.Qt.KeepAspectRatio)) return actions
def _setupFormats(self): '''Setup a different format for the different message types.''' fmap = {} fmt = QtGui.QTextCharFormat() fmt.setForeground(QtGui.QColor('red')) fmap['error'] = fmt fmt = QtGui.QTextCharFormat() fmt.setForeground(QtGui.QColor('orange')) fmap['warning'] = fmt fmt = QtGui.QTextCharFormat() fmt.setForeground(QtGui.QColor('blue')) fmap['info'] = fmt fmt = QtGui.QTextCharFormat() fmt.setForeground(QtGui.QColor('gray')) fmap['debug'] = fmt fmt = QtGui.QTextCharFormat() fmt.setFontWeight(QtGui.QFont.Bold) fmap['cmd'] = fmt return fmap
def plot(self, polygon): #~ if points[0] != points[-1]: #~ poly.append(poly[0]) # View box on the overview pen = QtGui.QPen(QtCore.Qt.SolidLine) pen.setColor(QtGui.QColor(QtCore.Qt.red)) item = self.graphicsview.scene().addPolygon(polygon, pen) item.setZValue(1) return item
def _setupHelpActions(self): actions = QtWidgets.QActionGroup(self) icon = QtGui.QIcon( ':/trolltech/styles/commonstyle/images/fileinfo-32.png') QtWidgets.QAction(icon, 'About', actions, triggered=self.about) icon = QtGui.QIcon(':/trolltech/qmessagebox/images/qtlogo-64.png') QtWidgets.QAction(icon, 'About Qt', actions, triggered=QtWidgets.QApplication.aboutQt) return actions
def _setupActions(self): actions = QtWidgets.QActionGroup(self) # Zoom in icon = qtsupport.geticon('zoom-in.svg', 'gsdview') QtWidgets.QAction(icon, self.tr('Zoom In'), actions, objectName='zoomInAction', statusTip=self.tr('Zoom In'), shortcut=QtGui.QKeySequence(self.tr('Ctrl++')), triggered=self.zoomIn) # Zoom out icon = qtsupport.geticon('zoom-out.svg', 'gsdview') QtWidgets.QAction(icon, self.tr('Zoom Out'), actions, objectName='zoomOutAction', statusTip=self.tr('Zoom Out'), shortcut=QtGui.QKeySequence(self.tr('Ctrl+-')), triggered=self.zoomOut) # Zoom fit icon = qtsupport.geticon('zoom-fit.svg', 'gsdview') QtWidgets.QAction(icon, self.tr('Zoom Fit'), actions, objectName='zoomFitAction', statusTip=self.tr('Zoom to fit the window size'), triggered=self.zoomFit) # Zoom 100 icon = qtsupport.geticon('zoom-100.svg', 'gsdview') QtWidgets.QAction(icon, self.tr('Zoom 100%'), actions, objectName='zoom100Action', statusTip=self.tr('Original size'), triggered=self.zoom100) # Manual Zoom #icon = QtGui.QIcon() #qt4support.geticon('zoom-100.svg', 'gsdview') #QtWidgets.QWidgetAction( # icon, self.tr('Zoom 100%'), actions, # statusTip=self.tr('Original size'), # triggered=self.zoom100) return actions
def setFootprint(self, polygon): self.clear() if not polygon: return lon = np.asarray([p.x() for p in polygon]) lat = np.asarray([p.y() for p in polygon]) mlon = lon.mean() mlat = lat.mean() delta = mlon - utils.geonormalize(mlon) if delta: lon -= delta mlon -= delta polygon.translate(-delta, 0) self.box = self.plot(polygon) points = QtGui.QPolygonF([ QtCore.QPointF(mlon - self.bigBoxSize / 2., mlat - self.bigBoxSize / 2.), QtCore.QPointF(mlon + self.bigBoxSize / 2., mlat - self.bigBoxSize / 2.), QtCore.QPointF(mlon + self.bigBoxSize / 2., mlat + self.bigBoxSize / 2.), QtCore.QPointF(mlon - self.bigBoxSize / 2., mlat + self.bigBoxSize / 2.), ]) self.bigbox = self.plot(points) self.actionZoomIn.setEnabled(True)
def __init__(self, parent=None, flags=QtCore.Qt.WindowFlags(0), **kwargs): super(ItemModelMainWindow, self).__init__(parent, flags, **kwargs) #: main application datamodel (QStandardItemModel) self.datamodel = QtGui.QStandardItemModel(self) # @TODO: custom treeview with "currentChanged" slot re-implemented #: tree view for the main application data model self.treeview = QtWidgets.QTreeView() # @TODO #self.treeview.setSelectionMode(QtWidgets.QTreeView.SingleSelection) self.treeview.setModel(self.datamodel) self.treeview.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) self.treeview.header().hide() self.treeview.clicked.connect(self.setActiveWinFromIndex) self.mdiarea.subWindowActivated.connect(self.setActiveIndexFromWin) self.datamodel.rowsAboutToBeRemoved.connect(self.onItemsClosed) # setup the treeview dock treeviewdock = QtWidgets.QDockWidget(self.tr('Data Browser'), self) treeviewdock.setWidget(self.treeview) treeviewdock.setObjectName('TreeViewPanel') self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treeviewdock)
def __init__(self, parent=None, flags=QtCore.Qt.WindowFlags(0), **kwargs): super(QtBlinker, self).__init__(parent, flags, **kwargs) #qstyle = QtWidgets.QApplication.style() #pixmap = qstyle.standardPixmap(QtWidgets.QStyle.SP_MediaStop) pixmap = QtGui.QPixmap( ':/trolltech/styles/commonstyle/images/standardbutton-no-32.png') self.setPixmap(pixmap)
def _setupActions(self): actions = super(LayerManager, self)._setupActions() icon = QtGui.QIcon( ':/trolltech/styles/commonstyle/images/viewdetailed-128.png') QtWidgets.QAction(icon, self.tr('Select all'), actions, objectName='selectAllAction', statusTip=self.tr('Select all'), shortcut=self.tr('Ctrl-A'), triggered=self.view.selectAll) # connect actions action = actions.findChild(QtWidgets.QAction, 'moveToTopAction') action.triggered.connect(self.moveSelectionToTop) action = actions.findChild(QtWidgets.QAction, 'moveUpAction') action.triggered.connect(self.moveSelectionUp) action = actions.findChild(QtWidgets.QAction, 'moveDownAction') action.triggered.connect(self.moveSelectionDown) action = actions.findChild(QtWidgets.QAction, 'moveToBottomAction') action.triggered.connect(self.moveSelectionToBottom) action = actions.findChild(QtWidgets.QAction, 'removeLayerAction') action.triggered.connect(self.removeSelectedLayers) action = actions.findChild(QtWidgets.QAction, 'showLayerAction') action.triggered.connect(self.checkSelectedItems) action = actions.findChild(QtWidgets.QAction, 'hideLayerAction') action.triggered.connect(self.uncheckSelectedItems) return actions
def setItem(self, item): assert item.backend == 'gdalbackend' self.graphicsview.setUpdatesEnabled(False) try: self.reset() try: level = gdalsupport.ovrLevelForSize(item, self.OVRMAXSIZE) # @NOTE: use GREATER for overview level to ensure an overview # size smaller than OVRMAXSIZE ovrindex = gdalsupport.ovrBestIndex(item, level, 'GREATER') except gdalsupport.MissingOvrError: _log.info('no overview available or available overviews are ' 'too large') return scene = item.scene self.graphicsview.setScene(scene) self.graphicsview.setSceneRect(scene.sceneRect()) if not self.graphicsview.autoscale: ovrlevel = gdalsupport.ovrLevels(item)[ovrindex] matrix = QtGui.QMatirx3x3(ovrlevel, 0, 0, ovrlevel, 0, 0) self.graphicsview.setMatrix(matrix) else: self.graphicsview.fitInView() self.updateMainViewBox() finally: self.graphicsview.setUpdatesEnabled(True) self.graphicsview.update()
def autoscale(self, flag): self._autoscale = bool(flag) if self._autoscale: self.fitInView() else: self.setTransform(QtGui.QTransform()) self.update()
def __init__(self, *args, **kwargs): super(DoubleSpinBox, self).__init__(*args, **kwargs) self.lineEdit().setValidator(QtGui.QDoubleValidator(self)) self.setDecimals(7) self.setRange(-1e50, 1e50) qlocale = QtCore.QLocale('C') qlocale.setNumberOptions(QtCore.QLocale.OmitGroupSeparator) self.setLocale(qlocale)
def setViewContextActions(widget): assert (widget.contextMenuPolicy() == QtCore.Qt.ActionsContextMenu), \ 'menu policy is not "QtCore.Qt.ActionsContextMenu"' #if widget.contextMenuPolicy() != QtCore.Qt.ActionsContextMenu: # widget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) icon = geticon('copy.svg', __name__) action = QtWidgets.QAction( icon, widget.tr('&Copy'), widget, objectName='copyAction', shortcut=widget.tr('Ctrl+C'), toolTip=widget.tr('Copy selected items'), triggered=lambda: copySelectedItems(widget)) widget.addAction(action) #':/trolltech/dialogs/qprintpreviewdialog/images/view-page-multi-32.png' icon = QtGui.QIcon( ':/trolltech/styles/commonstyle/images/viewlist-128.png') action = QtWidgets.QAction( icon, widget.tr('Select &All'), widget, objectName='selectAllAction', #shortcut=widget.tr('Ctrl+A'), toolTip=widget.tr('Select all items'), triggered=lambda: selectAllItems(widget)) widget.addAction(action) icon = widget.style().standardIcon(QtWidgets.QStyle.SP_DialogSaveButton) action = QtWidgets.QAction( icon, widget.tr('&Save As'), widget, objectName='saveAsAction', shortcut=widget.tr('Ctrl+S'), statusTip=widget.tr('Save as'), triggered=lambda: exportTable(widget.model())) widget.addAction(action) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/print-32.png') action = QtWidgets.QAction( icon, widget.tr('&Print'), widget, objectName='printAction', shortcut=widget.tr('Ctrl+P'), statusTip=widget.tr('Print'), triggered=lambda: printObject(widget)) widget.addAction(action)
def numpy2qimage(data, colortable=GRAY_COLORTABLE): '''Convert a numpy array into a QImage. .. note:: requires sip >= 4.7.5. ''' has_colortable = False if data.dtype in (np.uint8, np.ubyte, np.byte): if data.ndim == 2: h, w = data.shape image = _aligned(data) format_ = QtGui.QImage.Format_Indexed8 has_colortable = True elif data.ndim == 3 and data.shape[2] == 3: h, w = data.shape[:2] image = np.zeros((h, w, 4), data.dtype) image[:, :, 2::-1] = data image[..., -1] = 255 format_ = QtGui.QImage.Format_RGB32 elif data.ndim == 3 and data.shape[2] == 4: h, w = data.shape[:2] image = np.require(data, np.uint8, 'CO') # 'CAO' format_ = QtGui.QImage.Format_ARGB32 else: raise ValueError('unable to convert data: shape=%s, ' 'dtype="%s"' % (data.shape, np.dtype(data.dtype))) elif data.dtype == np.uint16 and data.ndim == 2: # @TODO: check h, w = data.shape image = _aligned(data) format_ = QtGui.QImage.Format_RGB16 elif data.dtype == np.uint32 and data.ndim == 2: h, w = data.shape image = np.require(data, data.dtype, 'CO') # 'CAO' #format_ = QtGui.QImage.Format_ARGB32 format_ = QtGui.QImage.Format_RGB32 else: raise ValueError( 'unable to convert data: shape=%s, dtype="%s"' % ( data.shape, np.dtype(data.dtype))) result = QtGui.QImage(image.data, w, h, format_) result.ndarray = image if has_colortable: result.setColorTable(colortable) return result
def setWorldmapItem(self, resolution='low'): scene = self.graphicsview.scene() if self.worldmapitem is not None: scene.removeItem(self.worldmapitem) #~ imgfile = qt4support.geticonfile('world_2160x1080.jpg', __name__) imgfile = qtsupport.geticonfile('world_4320x2160.jpg', __name__) #~ imgfile = qt4support.geticonfile('world_5400x2700.jpg', __name__) worldmap = QtGui.QPixmap(imgfile) worldmapitem = scene.addPixmap(worldmap) worldmapitem.setTransformationMode(QtCore.Qt.SmoothTransformation) # @NOTE: reverse the y axis worldmapitem.setTransform( QtGui.QTransform(360. / worldmap.width(), 0, 0, -180. / worldmap.height(), -180, 90)) self.worldmapitem = worldmapitem
def __init__(self, parent=None, **kwargs): super(NavigationGraphicsView, self).__init__(parent, **kwargs) self._viewbox = None self._autoscale = True self.setMouseTracking(True) # default pen self._pen = QtGui.QPen() self._pen.setColor(self.BOXCOLOR) self._pen.setWidth(self.BOXWIDTH)
def openvector(self, filename): # @TODO: check limits MAX_LAYER_COUNT = 10 srs = None transform = None affine_transform = None # @TODO: remove #srs = osr.SpatialReference() #srs.SetLCC(20, 20, 20, 0, 0, 0) ##srs.SetUTM(33) # @TODO: remove #~ from math import sin, cos, radians #~ a = radians(-45) #~ qtransform = QtGui.QTransform( #~ cos(a), -sin(a), sin(a), cos(a), 0, 0) #~ #affine_transform = qtransform #~ transform = lambda x, y, z: qtransform.map(x, y) ds = ogr.Open(filename) if ds is None: raise ValueError('unable to open "$s"' % filename) if ds.GetLayerCount() > MAX_LAYER_COUNT: raise RuntimeError('too many layers: %d' % ds.GetLayerCount()) for index, layer in enumerate(ds): qlayer = ogrqt.layerToGraphicsItem(layer, srs, transform) #qlayer.datasource = ds.GetName() #qlayer.index = index qlayer.setData(ogrqt.DATAKEY['datasource'], ds.GetName()) qlayer.setData(ogrqt.DATAKEY['index'], index) if affine_transform: qlayer.setTransform(affine_transform) if qlayer.childItems(): self.scene.addItem(qlayer) item = QtGui.QStandardItem(layer.GetName()) item.setCheckable(True) item.setCheckState(QtCore.Qt.Checked) item.setData(qlayer) item.setToolTip( self.tr('Layer "%s": %d features.' % (layer.GetName(), len(qlayer.childItems())))) self.model.appendRow(item) self.treeview.resizeColumnToContents(0)
def geticon(name, package=None): '''Build and return requested icon. It is assumed that icon files are located in the "images" subfolder of the package. .. seealso:: :func:`gsdview.utils.getresource` ''' iconfile = utils.getresource(os.path.join('images', name), package) return QtGui.QIcon(iconfile)
def _newModeAction(self, mode, parent): if isinstance(mode.icon, string_types): icon = QtGui.QIcon(mode.icon) elif isinstance(mode.icon, QtWidgets.QStyle.StandardPixmap): style = QtWidgets.QApplication.style() icon = style.standardIcon(mode.icon) else: icon = mode.icon action = QtWidgets.QAction( icon, self.tr(mode.label), parent, statusTip=self.tr(mode.label), checkable=True) action.triggered.connect(lambda: self.modeChanged.emit(self.mode)) return action
def _setupActions(self): actions = QtWidgets.QActionGroup(self) # Zoom in icon = qtsupport.geticon('zoom-in.svg', 'gsdview') QtWidgets.QAction( icon, self.tr('Zoom In'), actions, objectName='zoomOutAction', statusTip=self.tr('Zoom In'), shortcut=QtGui.QKeySequence(self.tr('Ctrl++')), enabled=False, triggered=lambda: self._zoom(+1)) # Zoom out icon = qtsupport.geticon('zoom-out.svg', 'gsdview') QtWidgets.QAction( icon, self.tr('Zoom Out'), actions, objectName='zoomOutAction', statusTip=self.tr('Zoom Out'), shortcut=QtGui.QKeySequence(self.tr('Ctrl+-')), enabled=False, triggered=lambda: self._zoom(-1)) return actions
def gdalcolorentry2qcolor(colrentry, interpretation=gdal.GPI_RGB): qcolor = QtGui.QColor() if interpretation == gdal.GPI_RGB: qcolor.setRgb(colrentry.c1, colrentry.c2, colrentry.c3, colrentry.c4) elif interpretation == gdal.GPI_Gray: qcolor.setRgb(colrentry.c1, colrentry.c1, colrentry.c1) elif interpretation == gdal.GPI_CMYK: qcolor.setCmyk(colrentry.c1, colrentry.c2, colrentry.c3, colrentry.c4) elif interpretation == gdal.GPI_HLS: qcolor.setHsv(colrentry.c1, colrentry.c2, colrentry.c3) # , colrentry.c4) else: raise ValueError('invalid color intepretatin: "%s"' % interpretation) return qcolor
def _setupFileActions(self): style = self.style() actions = QtWidgets.QActionGroup(self) icon = style.standardIcon(QtWidgets.QStyle.SP_DialogOpenButton) QtWidgets.QAction(icon, self.tr('&Open'), actions, objectName='openAction', shortcut=self.tr('Ctrl+O'), statusTip=self.tr('Open'), triggered=self.onOpen) icon = style.standardIcon(QtWidgets.QStyle.SP_DialogSaveButton) QtWidgets.QAction(icon, self.tr('&Save As'), actions, objectName='saveAsAction', shortcut=self.tr('Ctrl+S'), statusTip=self.tr('Save as'), triggered=self.onSave) icon = QtGui.QIcon( ':/trolltech/dialogs/qprintpreviewdialog/images/print-32.png') QtWidgets.QAction(icon, self.tr('&Print'), actions, objectName='printAction', shortcut=self.tr('Ctrl+P'), statusTip=self.tr('Print'), triggered=self.onPrint) QtWidgets.QAction(actions).setSeparator(True) icon = style.standardIcon(QtWidgets.QStyle.SP_DialogCancelButton) QtWidgets.QAction(icon, self.tr('&Quit'), actions, objectName='exitAction', shortcut=self.tr('Ctrl+Q'), statusTip=self.tr('Quit'), triggered=self.close) return actions
def _setupActions(self): qstype = QtWidgets.QApplication.style() # Setup actions self.actions = QtWidgets.QActionGroup(self) # Save As icon = qstype.standardIcon(QtWidgets.QStyle.SP_DialogSaveButton) self.actionSaveAs = QtWidgets.QAction( icon, self.tr('&Save As'), self, shortcut=self.tr('Ctrl+S'), statusTip=self.tr('Save text to file'), triggered=self.save) self.actions.addAction(self.actionSaveAs) # Clear icon = QtGui.QIcon(':/trolltech/styles/commonstyle/images/' 'standardbutton-clear-32.png') self.actionClear = QtWidgets.QAction( icon, self.tr('&Clear'), self, shortcut=self.tr('Shift+F5'), statusTip=self.tr('Clear the text'), triggered=self.clear) self.actions.addAction(self.actionClear) # Close icon = qstype.standardIcon(QtWidgets.QStyle.SP_DialogCloseButton) self.actionHide = QtWidgets.QAction( icon, self.tr('&Hide'), self, shortcut=self.tr('Ctrl+W'), statusTip=self.tr('Hide the text pane'), triggered=self.paneHideRequest) self.actions.addAction(self.actionHide)
def onOpen(self): filters = [ self.tr('All files (*)'), ] filters.extend('%s file (*.%s)' % (str(f).upper(), str(f)) for f in QtGui.QImageReader.supportedImageFormats()) filename, filter_ = QtWidgets.QFileDialog.getOpenFileName( self, self.tr('Load picture'), QtCore.QDir.home().absolutePath(), ';;'.join(filters)) # , filters[1]) if filename: if '.svg' in filename: item = QtSvg.QGraphicsSvgItem(filename) else: image = QtGui.QImage(filename) item = QtWidgets.QGraphicsPixmapItem(image) item.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True) item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) self.scene.addItem(item)
def __init__(self, parent=None, flags=QtCore.Qt.WindowFlags(0)): QtWidgets.QMainWindow.__init__(self, parent, flags) self.statusBar().show() self.model = QtGui.QStandardItemModel(self) self.model.setColumnCount(2) self.treeview = QtWidgets.QTreeView() self.treeview.setModel(self.model) self.treeview.setHeaderHidden(True) self.treeview.setIndentation(0) self.treeview.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) self.treeview.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.treeview.header().setStretchLastSection(True) self.treedock = QtWidgets.QDockWidget(self.tr('Layers View'), self) self.treedock.setWidget(self.treeview) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.treedock) self.scene = QtWidgets.QGraphicsScene(self) self.graphicsview = QtWidgets.QGraphicsView(self.scene, self) self.setCentralWidget(self.graphicsview) self.mousemanager = MouseManager(self) self.mousemanager.register(self.graphicsview) self.mousemanager.mode = 'hand' self.layermanager = LayerManager(self.treeview, self) # File Actions self.fileactions = self._setupFileActions() menu = QtWidgets.QMenu('File', self) menu.addActions(self.fileactions.actions()) self.menuBar().addMenu(menu) self._filemenu = menu toolbar = QtWidgets.QToolBar('File toolbar', self) toolbar.addActions(self.fileactions.actions()) self.addToolBar(toolbar) # Mouse Actions menu = QtWidgets.QMenu('Mouse', self) menu.addActions(self.mousemanager.actions.actions()) self.menuBar().addMenu(menu) toolbar = QtWidgets.QToolBar('Mouse toolbar') toolbar.addActions(self.mousemanager.actions.actions()) self.addToolBar(toolbar) # View Actions self.viewactions = self._setupViewActions() menu = QtWidgets.QMenu('View', self) menu.addActions(self.viewactions.actions()) self.menuBar().addMenu(menu) toolbar = QtWidgets.QToolBar('View toolbar') toolbar.addActions(self.viewactions.actions()) self.addToolBar(toolbar) # Layer Actions layeractions = self.layermanager.actions menu = QtWidgets.QMenu('Layer', self) menu.addActions(layeractions.actions()) self.menuBar().addMenu(menu) toolbar = QtWidgets.QToolBar('Layer toolbar') toolbar.addActions(layeractions.actions()) self.addToolBar(toolbar) # Help action self.helpactions = self._setupHelpActions() menu = QtWidgets.QMenu('Help', self) menu.addActions(self.helpactions.actions()) self.menuBar().addMenu(menu) toolbar = QtWidgets.QToolBar('Help toolbar', self) toolbar.addActions(self.helpactions.actions()) self.addToolBar(toolbar) self.resize(900, 500) self.reset() self.statusBar().showMessage('Ready')
class MouseMode(QtCore.QObject): '''Base class for mouse mode desctiptors. Qt Graphics Framework mouse mode descriptors define some basic property for mouse related matters: - cursor - dragmode - eventFilter - name - label - icon The first three properties (not to be intender as python progremming language property) are strongly characterizing of the way the mouse works. In particular the eventFilter method is used to filter all events coming from graphics scenes an graphics views. .. note:: in order to work properly the eventFilter should be installed on both graphics scene and view and also on the scrollbars of the graphics view. So please always use the register method of MouseManager for a proper installaton of al event filters. ''' dragmode = QtWidgets.QGraphicsView.NoDrag cursor = None icon = QtGui.QIcon() label = '' name = '' def eventFilter(self, obj, event): '''Basic implementation of the eventFilter method. The dafault implementation makes some basic operation such setting the mouse cursor anc dispatch the event to specific methods: - sceneEventFilter - viewEventFilter - scrollbarEventFilter In most of the cases derived classes only need to specialize one or more of this specific methods. ''' if isinstance(obj, QtWidgets.QGraphicsScene): return self.sceneEventFilter(obj, event) elif isinstance(obj, QtWidgets.QGraphicsView): if event.type() == QtCore.QEvent.Enter: obj.setDragMode(self.dragmode) if self.cursor: obj.setCursor(self.cursor) else: obj.unsetCursor() return self.viewEventFilter(obj, event) elif isinstance(obj, QtWidgets.QScrollBar): return self.scrollbarEventFilter(obj, event) else: return False def sceneEventFilter(self, obj, event): return False def viewEventFilter(self, obj, event): return False def scrollbarEventFilter(self, obj, event): return False
def __init__(self, parent, **kwargs): '''Constructs a QtWindowListMenu object. The *parent* parameter is passed to the QMenu constructor. Although this parameter has the conventional default of 0, you will normally want to explicitly provide a parent object, since the later adding of this menu object to an action container (e.g. QMenuBar) does not cause a reparenting. The container is normally the natural choice for *parent*. ''' super(QtWindowListMenu, self).__init__(parent, **kwargs) self.mdi = None self.setTitle(self.tr('&Windows')) self.aboutToShow.connect(self.syncWithMdiArea) self._stdGroup = QtWidgets.QActionGroup(self, exclusive=False) self._winGroup = QtWidgets.QActionGroup(self, exclusive=True) #, triggered=self.activateWindow) # @COMPATIBILITY: pyside 1.2.2 self._winGroup.triggered.connect(self.activateWindow) # Create the standard menu items. # @Note: Creation order must match the StandardAction enum values ;-) QtWidgets.QAction(self.tr('Cl&ose'), self._stdGroup, shortcut=self.tr('Ctrl+F4'), statusTip=self.tr('Close the active window')) QtWidgets.QAction(self.tr('Close &All'), self._stdGroup, statusTip=self.tr('Close all the windows')) act = self._stdGroup.addAction('') act.setSeparator(True) QtWidgets.QAction(self.tr('&Tile'), self._stdGroup, statusTip=self.tr('Tile the windows')) QtWidgets.QAction(self.tr('&Cascade'), self._stdGroup, statusTip=self.tr('Cascade the windows')) act = self._stdGroup.addAction('') act.setSeparator(True) QtWidgets.QAction( self.tr('Ne&xt'), self._stdGroup, statusTip=self.tr('Move the focus to the next window')) QtWidgets.QAction( self.tr('Pre&vious'), self._stdGroup, statusTip=self.tr('Move the focus to the previous window')) act = self._stdGroup.addAction('') act.setSeparator(True) self.addActions(self._stdGroup.actions()) self._winMap = {} # QMap<QAction *, QMdiSubWindow *> self._iconMap = {} # QMap<const QMdiSubWindow *, QIcon> self._defIcon = QtGui.QIcon()
def main(): # @IMPORTANT: force numeric locale to 'C' in order to avoid problems # with GDAL and PPROJ4 # @SEEALSO: http://trac.osgeo.org/gdal/wiki/FAQMiscellaneous#DoesGDALworkindifferentinternationalnumericlocales import os os.environ['LC_NUMERIC'] = 'C' args = parse_args() if args.log_level != 'NOTSET': loglevel = logging.getLevelName(args.log_level) else: loglevel = logging.INFO logging.basicConfig( level=loglevel, #format='%(levelname)s: %(message)s') format='%(asctime)s %(name)s %(levelname)s: %(message)s') # set the logging level explicitly on gsdview logger #logging.getLogger().setLevel(loglevel) logging.getLogger('gsdview').setLevel(loglevel) # PyQt loggers logging.getLogger('PyQt5.uic').setLevel(logging.WARNING) log = logging.getLogger(__name__) log.debug('log level set to %s', logging.getLevelName(log.level)) # @TODO: # * config logging using options.configfile, USER_CFG, SYS_CFG # * if options.debug: set rootlogger.level = logging.DEBUG # * maybe set loglevelfor other loggers timer = Timer() # splash screen ######################################################### from qtsix import QtWidgets, QtGui log.debug('Qt import: %d.%06ds', *timer.update()) import sys from gsdview.info import name as NAME from gsdview.info import version as VERSION from gsdview.utils import getresource app = QtWidgets.QApplication(sys.argv) app.setApplicationName(NAME) app.setApplicationVersion(VERSION) pngfile = getresource(os.path.join('images', 'splash.png'), __name__) pixmap = QtGui.QPixmap(pngfile) splash = QtWidgets.QSplashScreen(pixmap) splash.show() app.processEvents() splash_loghandler = SplashLogHandler(splash, app) splash_loghandler.setFormatter(logging.Formatter('%(message)s')) log.addHandler(splash_loghandler) log.info('Splash screen setup completed') log.debug('splash screen setup: %d.%06ds', *timer.update()) # modules loading ####################################################### preload(MODULES, app) # GUI ################################################################### log.info('Build GUI ...') from gsdview.app import GSDView # @TODO: pass plugins_path?? mainwin = GSDView(loglevel=args.log_level) mainwin.show() log.info('GUI setup completed') log.debug('GUI setup: %d.%06ds', *timer.update()) # close splash and run app ############################################## log.removeHandler(splash_loghandler) splash.finish(mainwin) app.processEvents() log.info('Install the exception hook') sys.excepthook = mainwin.excepthook # @TODO: check log.info('Enter main event loop') # @COMPATIBILITY: this will raise the window on Mac OS X mainwin.raise_() sys.exit(app.exec_())