Exemplo n.º 1
0
    def __init__(self, parentWidget, label_text_NotSelected,
                 label_text_Selected, model):
        """Constructor"""

        QObject.__init__(self)

        self.model = model

        self.gridLayout = QGridLayout(parentWidget)

        self.verticalLayout_left_list = QVBoxLayout()
        self.label_NotSelected = QLabel(parentWidget)
        self.label_NotSelected.setText(label_text_NotSelected)
        self.verticalLayout_left_list.addWidget(self.label_NotSelected)
        self.listView_NotSelected = QListView(parentWidget)
        self.verticalLayout_left_list.addWidget(self.listView_NotSelected)
        self.gridLayout.addLayout(self.verticalLayout_left_list, 0, 0, 1, 2)

        self.verticalLayout_right_left = QVBoxLayout()
        spacerItem = QSpacerItem(20, 178, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_right_left.addItem(spacerItem)
        self.pushButton_right_arrow = QPushButton(parentWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalPolicy(0)
        sizePolicy.setHeightForWidth(
            self.pushButton_right_arrow.sizePolicy().hasHeightForWidth())
        self.pushButton_right_arrow.setSizePolicy(sizePolicy)
        self.pushButton_right_arrow.setMinimumSize(QSize(50, 50))
        self.pushButton_right_arrow.setMaximumSize(QSize(50, 50))
        self.pushButton_right_arrow.setIcon(QIcon(':/right_arrow.png'))
        self.pushButton_right_arrow.setIconSize(QSize(50, 50))
        self.pushButton_right_arrow.setText('')
        self.verticalLayout_right_left.addWidget(self.pushButton_right_arrow)
        self.pushButton_left_arrow = QPushButton(parentWidget)
        sizePolicy.setHeightForWidth(
            self.pushButton_left_arrow.sizePolicy().hasHeightForWidth())
        self.pushButton_left_arrow.setSizePolicy(sizePolicy)
        self.pushButton_left_arrow.setMinimumSize(QSize(50, 50))
        self.pushButton_left_arrow.setMaximumSize(QSize(50, 50))
        self.pushButton_left_arrow.setIcon(QIcon(':/left_arrow.png'))
        self.pushButton_left_arrow.setIconSize(QSize(50, 50))
        self.pushButton_left_arrow.setText('')
        self.verticalLayout_right_left.addWidget(self.pushButton_left_arrow)
        spacerItem = QSpacerItem(20, 178, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_right_left.addItem(spacerItem)
        self.gridLayout.addLayout(self.verticalLayout_right_left, 0, 2, 1, 1)

        self.verticalLayout_right_list = QVBoxLayout()
        self.label_Selected = QLabel(parentWidget)
        self.label_Selected.setText(label_text_Selected)
        self.verticalLayout_right_list.addWidget(self.label_Selected)
        self.listView_Selected = QListView(parentWidget)
        self.verticalLayout_right_list.addWidget(self.listView_Selected)
        self.gridLayout.addLayout(self.verticalLayout_right_list, 0, 3, 1, 2)

        self.verticalLayout_up_down = QVBoxLayout()
        spacerItem = QSpacerItem(20, 178, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_up_down.addItem(spacerItem)
        self.pushButton_up_arrow = QPushButton(parentWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalPolicy(0)
        sizePolicy.setHeightForWidth(
            self.pushButton_up_arrow.sizePolicy().hasHeightForWidth())
        self.pushButton_up_arrow.setSizePolicy(sizePolicy)
        self.pushButton_up_arrow.setMinimumSize(QSize(50, 50))
        self.pushButton_up_arrow.setMaximumSize(QSize(50, 50))
        self.pushButton_up_arrow.setIcon(QIcon(':/up_arrow.png'))
        self.pushButton_up_arrow.setIconSize(QSize(50, 50))
        self.pushButton_up_arrow.setText('')
        self.verticalLayout_up_down.addWidget(self.pushButton_up_arrow)
        self.pushButton_down_arrow = QPushButton(parentWidget)
        sizePolicy.setHeightForWidth(
            self.pushButton_down_arrow.sizePolicy().hasHeightForWidth())
        self.pushButton_down_arrow.setSizePolicy(sizePolicy)
        self.pushButton_down_arrow.setMinimumSize(QSize(50, 50))
        self.pushButton_down_arrow.setMaximumSize(QSize(50, 50))
        self.pushButton_down_arrow.setIcon(QIcon(':/down_arrow.png'))
        self.pushButton_down_arrow.setIconSize(QSize(50, 50))
        self.pushButton_down_arrow.setText('')
        self.verticalLayout_up_down.addWidget(self.pushButton_down_arrow)
        spacerItem = QSpacerItem(20, 178, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_up_down.addItem(spacerItem)
        self.gridLayout.addLayout(self.verticalLayout_up_down, 0, 5, 1, 1)

        self.listView_NotSelected.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.listView_Selected.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        self.listView_NotSelected.setModel(self.model.model_NotSelected)
        self.listView_Selected.setModel(self.model.model_Selected)
Exemplo n.º 2
0
 def sizeHint(self):
     size = self.zoom * self.image.size()
     if self.zoom >= 3:
         size += QSize(1, 1)
     return size
Exemplo n.º 3
0
 def minimumSizeHint(self):
     return QSize(10, 10)
Exemplo n.º 4
0
 def sizeHint(self):
     return QSize(200, 200)
Exemplo n.º 5
0
    def renderedImage(self,
                      width,
                      height,
                      extent,
                      transp_background=False,
                      layerids=None):
        if QGis.QGIS_VERSION_INT < 20700:
            return self._renderedImage2(width, height, extent,
                                        transp_background, layerids)

        # render layers with QgsMapRendererCustomPainterJob
        from qgis.core import QgsMapRendererCustomPainterJob
        antialias = True
        settings = self.exportSettings.mapSettings

        # store old map settings
        old_outputSize = settings.outputSize()
        old_extent = settings.extent()
        old_rotation = settings.rotation()
        old_layerids = settings.layers()
        old_backgroundColor = settings.backgroundColor()

        # map settings
        settings.setOutputSize(QSize(width, height))
        settings.setExtent(extent.unrotatedRect())
        settings.setRotation(extent.rotation())

        if layerids is not None:
            settings.setLayers(layerids)

        if transp_background:
            settings.setBackgroundColor(QColor(Qt.transparent))
        #else:    #TODO: remove
        #settings.setBackgroundColor(self.exportSettings.canvas.canvasColor())

        has_pluginlayer = False
        for layerId in settings.layers():
            layer = QgsMapLayerRegistry.instance().mapLayer(layerId)
            if layer and layer.type() == QgsMapLayer.PluginLayer:
                has_pluginlayer = True
                break

        # create an image
        image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
        painter = QPainter()
        painter.begin(image)
        if antialias:
            painter.setRenderHint(QPainter.Antialiasing)

        # rendering
        job = QgsMapRendererCustomPainterJob(settings, painter)
        if has_pluginlayer:
            job.renderSynchronously(
            )  # use this method so that TileLayerPlugin layer is rendered correctly
        else:
            job.start()
            job.waitForFinished()
        painter.end()

        # restore map settings
        settings.setOutputSize(old_outputSize)
        settings.setExtent(old_extent)
        settings.setRotation(old_rotation)
        settings.setLayers(old_layerids)
        settings.setBackgroundColor(old_backgroundColor)

        return tools.base64image(image)
Exemplo n.º 6
0
 def resizeEvent(self, qResizeEvent):
     if not qResizeEvent.oldSize() == QSize(-1, -1) and self.text() != "":
         #print("Adjust because of resize")
         self.adjustFont()
     return QPushButton.resizeEvent(self, qResizeEvent)
Exemplo n.º 7
0
 def sizeHint(self):
     """Initial size"""
     return QSize(750, 490)
Exemplo n.º 8
0
    def updateDisplay(self):
        ''' Add map(s) of all QF components to the canvas based on what's selected in self.lstTimes'''
        timestamps = [
            pd.datetime.strptime(newItem.text(), '%Y-%m-%d %H:%M')
            for newItem in self.lstTimes.selectedItems()
        ]

        for t in timestamps:
            outs = pd.read_csv(self.model.getFileList()[t],
                               header=0,
                               index_col=0)
            outLayer = self.outputLayer
            # Make sure the output file is properly appended (this gets evaluated for non-extra-disaggregated datasets)
            # because I didn't set an output shapefile path properl

            if os.path.split(self.outputLayer)[0] == '':
                outLayer = os.path.join(self.model.downscaledPath,
                                        os.path.split(self.outputLayer)[1])

            fileToPopulate = self.outputLayer
            new_layer = populateShapefileFromTemplate(
                outs,
                self.featureIdField,
                outLayer,
                int(self.outputEPSG),
                title=t.strftime(' %Y-%m-%d %H:%M UTC'))

            # Set ranges suited to all the different QF types
            range_minima = [0, 0.000001, 0.1, 1, 10, 100]
            range_maxima = [0.000001, 0.1, 1, 10, 100, 1000]
            colours = [
                '#CECECE', '#FEE6CE', '#FDAE6B', '#F16913', '#D94801',
                '#7F2704'
            ]
            opacity = 1
            for component in self.componentTranslation.values():
                layerName = component + t.strftime(' %Y-%m-%d %H:%M UTC')
                if component == self.componentTranslation.values()[0]:
                    colourRanges(new_layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    new_layer.setLayerName(layerName)
                    layerId = new_layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(new_layer)
                    proportion = new_layer.extent().height(
                    ) / new_layer.extent().width()

                else:
                    # Have to clone. Can't seem to duplicate a map layer...
                    layer = duplicateVectorLayer(new_layer)
                    layer.setLayerName(layerName)
                    colourRanges(layer, component, opacity, range_minima,
                                 range_maxima, colours)
                    layerId = layer.id()
                    QgsMapLayerRegistry.instance().addMapLayer(layer)
                    proportion = layer.extent().height() / layer.extent(
                    ).width()

                maxSize = 2000  # Max size of output image
                if proportion > 1:
                    hSize = maxSize / proportion
                    vSize = maxSize
                else:
                    hSize = maxSize
                    vSize = maxSize * proportion

                # create image in proportion with layer
                img = QImage(QSize(hSize, vSize),
                             QImage.Format_ARGB32_Premultiplied)

                # set image's background color
                color = QColor(255, 255, 255)
                img.fill(color.rgb())

                # create painter
                p = QPainter()
                p.begin(img)
                p.setRenderHint(QPainter.Antialiasing)

                render = QgsMapRenderer()

                # set layer set
                lst = [layerId]  # add ID of every layer
                render.setLayerSet(lst)

                # set extent
                rect = QgsRectangle(render.fullExtent())
                rect.scale(1.1)
                render.setExtent(rect)

                # set output size
                render.setOutputSize(img.size(), img.logicalDpiX())

                # do the rendering
                render.render(p)
                p.end()

                # save image
                img.save(
                    os.path.join(
                        self.model.renderPath,
                        component + t.strftime('_%Y-%m-%d_%H-%M_UTC.png')),
                    "png")
Exemplo n.º 9
0
Arquivo: tree.py Projeto: kzwkt/dff
  def data(self, index, role):
    """
    \reimp

    Nodes' pointers are encapsulated in QStandardItem (role : Qt.UserRole + 1). Most
    of the data can only be retrieved only if the node is retrieved:

    * The node name
    * The node icon
    * ...

    To do so, the TreeModel.data() method calls the QStandardItemModel.data() method by passing
    the `index` parameter and `Qt.UserRole + 1` or `Qt.UserRole + 2` to it. In the second case, it
    retrieves a boolean used to know if the node is already expended and returns directly.

    \param index the index of the data we want to get
    \param role the role of the data we want to retrieve

    \return a QVariant containing the data, or an invalid QVariant if the data could not be retrieved.
    """
    if not index.isValid():
      return QVariant()
    # Qt.UserRole + 2 contain a boolean indicating if the node has already been expanded
    # in the tree.
    if role == Qt.UserRole + 3:
      return QStandardItemModel.data(self, index, role)
    if role == Qt.UserRole + 2:
      return QStandardItemModel.data(self, index, role)
    # call QStandardItemModel.data method with a Qt.UserRole + 1 to get the pointer on the node
    # (returns a invalid QVariant if the node or the data is None)
    data = QStandardItemModel.data(self, index, Qt.UserRole + 1)
    if not data.isValid():
      return data
    # getting the node or returning an invalid QVariant() if the node is not valid
    node = self.VFS.getNodeFromPointer(data.toULongLong()[0])
    if node == None:
      return QVariant()
    # if role == UserRole + 1, it means that the node itself must be returned (the pointer
    # on the node, encapsulated in a QVariant()
    if role == (Qt.UserRole + 1):
      return data
    # in other cases, returns the requires data  : icon, color, etc. or an invalid QVariant()
    # if the role does not correpond to anything.
    if role == Qt.DisplayRole :
      return QVariant(QString.fromUtf8(node.name()))
    if role == Qt.DecorationRole:
      pixmap = QPixmap(node.icon())
      if node.hasChildren():
        try:
          pfsobj = node.children()[0].fsobj().this
        except AttributeError:
  	  pfsobj = None
        try:
          nfsobj = node.fsobj().this
        except AttributeError:
	  nfsobj = None
        if pfsobj != nfsobj:
          pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio)
          painter = QPainter(pixmap)
          rootPixmap = QPixmap(":root")
          painter.drawPixmap(0, 0, rootPixmap)
          painter.end()
      return QVariant(QIcon(pixmap))

    if role == Qt.BackgroundRole:
      if index == self.currentIndex:
        palette = QPalette().color(QPalette.Highlight)
        return QVariant(QColor(palette))
    if role == Qt.ForegroundRole:
      if (index == self.currentIndex) and not node.isDeleted():
        palette = QPalette().color(QPalette.HighlightedText)
        return QVariant(QColor(palette))
      if node.isDeleted():
        return  QVariant(QColor(Qt.red))
    if self.ch == True:
      if role == Qt.CheckStateRole:
        if index.column() == 0:
          if long(node.this) in self.selection.get():
            return Qt.Checked
          else:
            return Qt.Unchecked

    return QVariant()
Exemplo n.º 10
0
 def sizeHint(self): # this makes the text box taller when launched than if I don't have it
     return QSize(self.document().idealWidth() + 5, self.maximumHeight())
Exemplo n.º 11
0
    def __init__(self, run_model, run_arguments, parent):
        QDialog.__init__(self, parent)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)
        self.setModal(True)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, BaseRunModel)
        self._run_model = run_model
        self._run_arguments = run_arguments

        layout = QVBoxLayout()
        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.simulations_tracker = SimulationsTracker()
        states = self.simulations_tracker.getStates()

        self.total_progress = SimpleProgress()
        layout.addWidget(self.total_progress)

        status_layout = QHBoxLayout()
        status_layout.addStretch()
        self.__status_label = QLabel()
        status_layout.addWidget(self.__status_label)
        status_layout.addStretch()
        layout.addLayout(status_layout)

        self.progress = Progress()
        self.progress.setIndeterminateColor(self.total_progress.color)
        for state in states:
            self.progress.addState(state.state, QColor(*state.color),
                                   100.0 * state.count / state.total_count)

        layout.addWidget(self.progress)

        legend_layout = QHBoxLayout()
        self.legends = {}
        for state in states:
            self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color))
            self.legends[state].updateLegend(state.name, 0, 0)
            legend_layout.addWidget(self.legends[state])

        layout.addLayout(legend_layout)

        self.running_time = QLabel("")

        ert = None
        if isinstance(run_model, BaseRunModel):
            ert = run_model.ert()

        self.plot_tool = PlotTool()
        self.plot_tool.setParent(None)
        self.plot_button = QPushButton(self.plot_tool.getName())
        self.plot_button.clicked.connect(self.plot_tool.trigger)
        self.plot_button.setEnabled(ert is not None)

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)

        button_layout = QHBoxLayout()

        size = 20
        spin_movie = resourceMovie("ide/loading.gif")
        spin_movie.setSpeed(60)
        spin_movie.setScaledSize(QSize(size, size))
        spin_movie.start()

        self.processing_animation = QLabel()
        self.processing_animation.setMaximumSize(QSize(size, size))
        self.processing_animation.setMinimumSize(QSize(size, size))
        self.processing_animation.setMovie(spin_movie)

        button_layout.addWidget(self.processing_animation)
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.plot_button)
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)

        layout.addStretch()
        layout.addLayout(button_layout)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)

        self.__updating = False
        self.__update_queued = False
        self.__simulation_started = False

        self.__update_timer = QTimer(self)
        self.__update_timer.setInterval(500)
        self.__update_timer.timeout.connect(self.updateRunStatus)
Exemplo n.º 12
0
 def set_LabelWidth(self, width):
     self.checkBox.setMinimumSize(QSize(width, 0))
     self.checkBox.setMaximumSize(QSize(width, 16777215))
Exemplo n.º 13
0
 def sizeHint(self):
     return QSize(450, 550)
Exemplo n.º 14
0
 def sizeHint(self):
     return QSize(1024, 720)
Exemplo n.º 15
0
    def _init_ui(self):
        namesBox = gui.vBox(self.controlArea, "Names")

        hbox = gui.hBox(namesBox, margin=0, spacing=0)
        gui.lineEdit(hbox, self, "attr1", "Variable X ",
                     controlWidth=80, orientation=Qt.Horizontal,
                     enterPlaceholder=True, callback=self._attr_name_changed)
        gui.separator(hbox, 18)
        hbox = gui.hBox(namesBox, margin=0, spacing=0)
        attr2 = gui.lineEdit(hbox, self, "attr2", "Variable Y ",
                             controlWidth=80, orientation=Qt.Horizontal,
                             enterPlaceholder=True,
                             callback=self._attr_name_changed)
        gui.checkBox(hbox, self, "hasAttr2", '', disables=attr2,
                     labelWidth=0,
                     callback=self.set_dimensions)
        gui.separator(namesBox)

        gui.widgetLabel(namesBox, "Labels")
        self.classValuesView = listView = QListView(
            selectionMode=QListView.SingleSelection,
            sizePolicy=QSizePolicy(QSizePolicy.Ignored,
                                   QSizePolicy.Maximum)
        )
        listView.setModel(self.class_model)
        itemmodels.select_row(listView, 0)
        namesBox.layout().addWidget(listView)

        self.addClassLabel = QAction(
            "+", self,
            toolTip="Add new class label",
            triggered=self.add_new_class_label
        )

        self.removeClassLabel = QAction(
            unicodedata.lookup("MINUS SIGN"), self,
            toolTip="Remove selected class label",
            triggered=self.remove_selected_class_label
        )

        actionsWidget = itemmodels.ModelActionsWidget(
            [self.addClassLabel, self.removeClassLabel], self
        )
        actionsWidget.layout().addStretch(10)
        actionsWidget.layout().setSpacing(1)
        namesBox.layout().addWidget(actionsWidget)

        tBox = gui.vBox(self.controlArea, "Tools", addSpace=True)
        buttonBox = gui.hBox(tBox)
        toolsBox = gui.widgetBox(buttonBox, orientation=QtGui.QGridLayout())

        self.toolActions = QtGui.QActionGroup(self)
        self.toolActions.setExclusive(True)
        self.toolButtons = []

        for i, (name, tooltip, tool, icon) in enumerate(self.TOOLS):
            action = QAction(
                name, self,
                toolTip=tooltip,
                checkable=tool.checkable,
                icon=QIcon(icon),
            )
            action.triggered.connect(partial(self.set_current_tool, tool))

            button = QtGui.QToolButton(
                iconSize=QSize(24, 24),
                toolButtonStyle=Qt.ToolButtonTextUnderIcon,
                sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.Fixed)
            )
            button.setDefaultAction(action)
            self.toolButtons.append((button, tool))

            toolsBox.layout().addWidget(button, i / 3, i % 3)
            self.toolActions.addAction(action)

        for column in range(3):
            toolsBox.layout().setColumnMinimumWidth(column, 10)
            toolsBox.layout().setColumnStretch(column, 1)

        undo = self.undo_stack.createUndoAction(self)
        redo = self.undo_stack.createRedoAction(self)

        undo.setShortcut(QtGui.QKeySequence.Undo)
        redo.setShortcut(QtGui.QKeySequence.Redo)

        self.addActions([undo, redo])

        gui.separator(tBox)
        indBox = gui.indentedBox(tBox, sep=8)
        form = QtGui.QFormLayout(
            formAlignment=Qt.AlignLeft,
            labelAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow
        )
        indBox.layout().addLayout(form)
        slider = gui.hSlider(
            indBox, self, "brushRadius", minValue=1, maxValue=100,
            createLabel=False
        )
        form.addRow("Radius", slider)

        slider = gui.hSlider(
            indBox, self, "density", None, minValue=1, maxValue=100,
            createLabel=False
        )

        form.addRow("Intensity", slider)

        gui.rubber(self.controlArea)
        gui.auto_commit(self.left_side, self, "autocommit",
                        "Send", "Send on change")

        # main area GUI
        viewbox = PaintViewBox(enableMouse=False)
        self.plotview = pg.PlotWidget(background="w", viewBox=viewbox)
        self.plotview.sizeHint = lambda: QSize(200, 100)  # Minimum size for 1-d painting
        self.plot = self.plotview.getPlotItem()

        axis_color = self.palette().color(QtGui.QPalette.Text)
        axis_pen = QtGui.QPen(axis_color)

        tickfont = QtGui.QFont(self.font())
        tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11))

        axis = self.plot.getAxis("bottom")
        axis.setLabel(self.attr1)
        axis.setPen(axis_pen)
        axis.setTickFont(tickfont)

        axis = self.plot.getAxis("left")
        axis.setLabel(self.attr2)
        axis.setPen(axis_pen)
        axis.setTickFont(tickfont)
        if not self.hasAttr2:
            self.plot.hideAxis('left')

        self.plot.hideButtons()
        self.plot.setXRange(0, 1, padding=0.01)

        self.mainArea.layout().addWidget(self.plotview)

        # enable brush tool
        self.toolActions.actions()[0].setChecked(True)
        self.set_current_tool(self.TOOLS[0][2])

        self.set_dimensions()
Exemplo n.º 16
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)

        self.shellOutWidget = QWidget(self)
        self.shellOutWidget.setLayout(QVBoxLayout())
        self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0)
        self.shellOutWidget.layout().addWidget(self.shellOut)

        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOutWidget)
        self.splitter.addWidget(self.shell)

        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)

        openExtEditorBt = QCoreApplication.translate(
            "PythonConsole", "Open in external editor")
        self.openInEditorButton = QAction(self)
        self.openInEditorButton.setCheckable(False)
        self.openInEditorButton.setEnabled(True)
        self.openInEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.openInEditorButton.setMenuRole(QAction.PreferencesRole)
        self.openInEditorButton.setIconVisibleInMenu(True)
        self.openInEditorButton.setToolTip(openExtEditorBt)
        self.openInEditorButton.setText(openExtEditorBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate(
            "PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(
            QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole",
                                                  "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole",
                                                 "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(16, 16))
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(16, 16))
        self.toolBarEditor.setMovable(False)
        self.toolBarEditor.setFloatable(False)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addAction(self.openInEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.shellOutWidget.layout().insertWidget(0, self.toolBar)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        self.lineEditFind.setPlaceholderText(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod,
                     SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)
Exemplo n.º 17
0
                break
        # --- update font size ---
        self.setFont(f)

    def setFont(self, qFont):
        #print("Setfont", qFont.pointSize())
        if self.maxFont is None and qFont.pointSize(
        ) != -1:  # only remember very first value
            self.maxFont = qFont
        return QPushButton.setFont(self, qFont)


if __name__ == "__main__":
    app = QApplication([])
    window = Scaling_QLabel()
    window.setMinimumSize(QSize(0, 81))
    font = QFont()
    font.setPointSize(54)
    window.setFont(font)
    window.setTextFormat(Qt.AutoText)
    window.setScaledContents(False)
    window.setWordWrap(True)
    window.setText("This is a Teststring")
    window.show()

    #window = Scaling_QPushButton_Icon()
    #window.setIcon(QIcon("../res/icons/home.png"))
    #window.setIconSize(window.sizeHint()*2)

    #window = Scaling_QPushButton_Text()
    #sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
Exemplo n.º 18
0
    def setCurrentAction(self, action):
        """
        Sets the current action for this widget that highlights the size
        for this toolbar.
        
        :param      action | <QAction>
        """
        if action == self._currentAction:
            return

        self._currentAction = action
        self.currentActionChanged.emit(action)

        labels = self.actionLabels()
        anim_grp = QParallelAnimationGroup(self)
        max_size = self.maximumPixmapSize()
        min_size = self.minimumPixmapSize()

        if action:
            label = self.labelForAction(action)
            index = labels.index(label)

            # create the highlight effect
            palette = self.palette()
            effect = QGraphicsDropShadowEffect(label)
            effect.setXOffset(0)
            effect.setYOffset(0)
            effect.setBlurRadius(20)
            effect.setColor(QColor(40, 40, 40))
            label.setGraphicsEffect(effect)

            offset = self.padding()
            if self.position() in (XDockToolbar.Position.East,
                                   XDockToolbar.Position.West):
                self.resize(max_size.width() + offset, self.height())

            elif self.position() in (XDockToolbar.Position.North,
                                     XDockToolbar.Position.South):
                self.resize(self.width(), max_size.height() + offset)

            w = max_size.width()
            h = max_size.height()
            dw = (max_size.width() - min_size.width()) / 3
            dh = (max_size.height() - min_size.height()) / 3

            for i in range(4):
                before = index - i
                after = index + i

                if 0 <= before and before < len(labels):
                    anim = XObjectAnimation(labels[before], 'setPixmapSize',
                                            anim_grp)

                    anim.setEasingCurve(self.easingCurve())
                    anim.setStartValue(labels[before].pixmapSize())
                    anim.setEndValue(QSize(w, h))
                    anim.setDuration(self.duration())
                    anim_grp.addAnimation(anim)

                    if i:
                        labels[before].setGraphicsEffect(None)

                if after != before and 0 <= after and after < len(labels):
                    anim = XObjectAnimation(labels[after], 'setPixmapSize',
                                            anim_grp)

                    anim.setEasingCurve(self.easingCurve())
                    anim.setStartValue(labels[after].pixmapSize())
                    anim.setEndValue(QSize(w, h))
                    anim.setDuration(self.duration())
                    anim_grp.addAnimation(anim)

                    if i:
                        labels[after].setGraphicsEffect(None)

                w -= dw
                h -= dh
        else:
            offset = self.padding()
            for label in self.actionLabels():
                # clear the graphics effect
                label.setGraphicsEffect(None)

                # create the animation
                anim = XObjectAnimation(label, 'setPixmapSize', self)
                anim.setEasingCurve(self.easingCurve())
                anim.setStartValue(label.pixmapSize())
                anim.setEndValue(min_size)
                anim.setDuration(self.duration())
                anim_grp.addAnimation(anim)

            anim_grp.finished.connect(self.resizeToMinimum)

        anim_grp.start()
        self._animating = True
        anim_grp.finished.connect(anim_grp.deleteLater)
        anim_grp.finished.connect(self.__markAnimatingFinished)

        if self._currentAction:
            self._hoverTimer.start()
        else:
            self._hoverTimer.stop()
Exemplo n.º 19
0
 def resizeEvent(self, qResizeEvent):
     if not qResizeEvent.oldSize() == QSize(-1, -1) and self.text() != "":
         self.adjustFont()
     return QLabel.resizeEvent(self, qResizeEvent)
Exemplo n.º 20
0
    def generatePlayblast(self,
                          fileName,
                          frameRange=None,
                          resolution=None,
                          slate=None,
                          effects=True,
                          geometryOnly=True,
                          pathFormat=r'{basePath}\{fileName}.{frame}.{ext}'):
        """
			Creates an unpadded JPG file sequence from the viewport for a given range.
		"""

        # Treating inputs.
        if isinstance(frameRange, int):
            frameRange = FrameRange([frameRange, frameRange])

        # Checking frame range.
        initialFrameRange = self._scene.animationRange()
        if not frameRange:
            frameRange = initialFrameRange

        # Collecting data.
        nativeCamera = self._nativeCamera()

        def genImagePath(frame=None):
            basePath, fn = os.path.split(fileName)
            pf = pathFormat
            # Deal with xsi's special number padding format
            if frame == None:
                filen = '(fn)'
                ext = '(ext)'
                # Remove any number specific formatting so we can insert a simple # for each padding digit
                pf = re.sub(r'{frame:[^}]*', r'{frame', pf)
                padding = re.findall(r'{frame:(\d+)', pathFormat)
                if padding:
                    frameNo = '#' * int(padding[0])
                else:
                    frameNo = '#'
            else:
                fileSplit = fn.split('.')
                filen = '.'.join(fileSplit[:-1])
                ext = fileSplit[-1]
                frameNo = frame
            out = pf.format(basePath=basePath,
                            fileName=filen,
                            frame=frameNo,
                            ext=ext)
            index = pathFormat.find('{ext}')
            if frame == None and index > 0 and pathFormat[index - 1] == '.':
                # strip out the file extension dot
                fileSplit = out.split('.')
                out = '.'.join(fileSplit[:-1]) + fileSplit[-1]
            return out

        firstFrameFileName = genImagePath(frameRange[0])
        lastFrameFileName = genImagePath(frameRange[1])

        try:
            firstFrameStartTime = os.path.getmtime(firstFrameFileName)
            lastFrameStartTime = os.path.getmtime(lastFrameFileName)
        except os.error:
            firstFrameStartTime = 0
            lastFrameStartTime = 0

        # Storing object states.
        self._scene.storeState()
        self.storeViewOptions()

        # Setting slate.
        if slate:
            self.setSlateText(slate)
            self.setSlateIsActive(True)
            xsi.SetValue(nativeCamera.FullName + '.camvis.currenttime', False)
        elif slate == None:
            xsi.SetValue(nativeCamera.FullName + '.camvis.currenttime', False)
        else:
            xsi.SetValue(nativeCamera.FullName + '.camvis.currenttime', True)

        # Setting regular visibility options.
        nativeCamera.Properties('Camera Visibility').Parameters(
            'gridvis').Value = False
        nativeCamera.Properties('Camera Visibility').Parameters(
            'gridaxisvis').Value = False
        nativeCamera.Properties('Camera Visibility').Parameters(
            'constructionlevel').Value = False
        nativeCamera.Properties('Camera Visibility').Parameters(
            'objannotationobjects').Value = False
        xsi.SetValue('preferences.ViewCube.show', False)

        if geometryOnly:

            # Setting geometry only visibility options.
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objpolymesh').Value = True
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objparticles').Value = True
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objinstances').Value = True
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objlights').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objcameras').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objimpgeometry').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objcurves').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objhair').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objnulls').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrltransfogroups').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlchnjnts').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlchnroots').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlchneff').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrllattices').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrltextsupp').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlchnjnts').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlwaves').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objctrlother').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'objenvironment').Value = False
            nativeCamera.Properties('Camera Visibility').Parameters(
                'custominfo').Value = False

        # Checking resolution.
        if not resolution:
            resolution = QSize(
                xsi.GetValue("Passes.RenderOptions.ImageWidth"),
                xsi.GetValue("Passes.RenderOptions.ImageHeight"))

        # Setting the scene range. Apparently if you don't it causes an animation layer issue.
        if not initialFrameRange.contains(frameRange):
            self._scene.setAnimationRange(frameRange)

        # Set camera's picture ratio.
        camera = self.camera()
        if camera:
            pictureRatio = camera.pictureRatio()
            camera.setPictureRatio(
                float(resolution.width()) / resolution.height())

        fps = self._scene.animationFPS()

        viewportCapture = xsi.Dictionary.GetObject(
            'ViewportCapture').NestedObjects

        viewportCapture('File Name').Value = fileName
        viewportCapture('Padding').Value = os.path.basename(genImagePath())
        viewportCapture('Width').Value = resolution.width()
        viewportCapture('Height').Value = resolution.height()
        viewportCapture('Scale Factor').Value = 1
        viewportCapture('User Pixel Ratio').Value = True
        viewportCapture('Pixel Ratio').Value = 1
        viewportCapture('Frame Rate').Value = fps
        viewportCapture('Write Alpha').Value = False
        viewportCapture('Record Audio Track').Value = False
        viewportCapture('Start Frame').Value = frameRange[0]
        viewportCapture('End Frame').Value = frameRange[1]
        viewportCapture('Launch Flipbook').Value = False
        viewportCapture('Use Native Movie Player').Value = False
        viewportCapture('Movie').Value = False
        viewportCapture('OpenGL Anti-Aliasing').Value = 16 if effects else 1
        viewportCapture('Remember Last Sequence').Value = False

        letterToNumber = {"A": 1, "B": 2, "C": 3, "D": 4}
        xsi.CaptureViewport(letterToNumber[self.name], False)

        # Restoring states.
        self._scene.restoreViewOptions()
        self.restoreViewOptions()

        if camera:
            camera.setPictureRatio(pictureRatio)

        # If the famous capture Softimage bug happened we raise a specific error.
        try:
            firstFrameEndTime = os.path.getmtime(firstFrameFileName)
            if not firstFrameStartTime < firstFrameEndTime:
                raise Exceptions.OutputFailed(
                    'The playblast failed due to a native Softimage bug. Do not panic, the fix is easy. Open the regular capture window, change the format to anything. Close the window and try again.'
                )
        except os.error:
            raise Exceptions.OutputFailed(
                'The playblast failed due to a native Softimage bug. Do not panic, the fix is easy. Open the regular capture window, change the format to anything. Close the window and try again.'
            )

        # If the capture was not completed we just return False.
        try:
            lastFrameEndTime = os.path.getmtime(lastFrameFileName)
            if not lastFrameStartTime < lastFrameEndTime:
                return False
        except os.error:
            return False

        return True
Exemplo n.º 21
0
 def convert(self, event):
     node = event.config.node
     buff = ""
     if (str(node.dataType()).find('video') != -1):
         if VIDEO_API_EXISTS:
             try:
                 md = video.VideoDecoder(node)
                 if event.config.frames == 1:
                     img = md.thumbnailAtPercent(event.config.percent,
                                                 event.config.size)
                 else:
                     img = QImage(
                         event.config.size * event.config.frames / 2,
                         event.config.size * 2, 4)
                     img.fill(0)
                     painter = QPainter(img)
                     for y in range(0, 2):
                         try:
                             for x in range(1, event.config.frames / 2 + 1):
                                 try:
                                     frame = md.thumbnailAtPercent(
                                         (x +
                                          ((event.config.frames / 2) * y)) *
                                         (100 / event.config.frames),
                                         event.config.size)
                                     painter.drawImage(
                                         (x - 1) * event.config.size,
                                         y * event.config.size, frame)
                                 except RuntimeError, e:
                                     raise e
                         except RuntimeError:
                             break
                     painter.end()
                 self.emit(SIGNAL("scaledFinished"), event.config, img)
                 return
             except:
                 pass
         self.emit(SIGNAL("scaledFinished"), event.config, None)
         return
     img = QImage()
     load = None
     buff = ""
     if str(node.dataType()).find(
             'jpeg') != -1 and node.size() < self.imageMaximumSize:
         try:
             buff = self.jpegInternalThumbnail(node)
             if (buff):
                 load = img.loadFromData(buff, 'jpeg')
                 if load == False:
                     buff = ""
         except IOError:
             buff = ""
     if not len(buff) and node.size() < self.imageMaximumSize:
         try:
             f = node.open()
             buff = f.read()
             f.close()
             load = img.loadFromData(buff)
         except IOError:
             load = False
     if load:
         img = img.scaled(QSize(event.config.size, event.config.size),
                          Qt.KeepAspectRatio, Qt.FastTransformation)
         self.emit(SIGNAL("scaledFinished"), event.config, img)
         return
     self.emit(SIGNAL("scaledFinished"), event.config, None)
     return
Exemplo n.º 22
0
 def sizeHint(self):
     return QSize(500, 500)
Exemplo n.º 23
0
 def sizeHint(self):
     return QSize(10, 10)
Exemplo n.º 24
0
 def sizeHint(self):
     return QSize(800, 600)
Exemplo n.º 25
0
 def newCleanImage(self, size=None):
     if size:
         self.size = QSize(*size)
     self.image = QImage(self.size, QImage.Format_Mono)
     self.clearIconImage()
Exemplo n.º 26
0
    def __init__(self):
        super().__init__()

        self.matrix = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._sort_indices = None
        self._selection = None

        self.sorting_cb = gui.comboBox(
            self.controlArea,
            self,
            "sorting",
            box="Element sorting",
            items=["None", "Clustering", "Clustering with ordered leaves"],
            callback=self._invalidate_ordering)

        box = gui.vBox(self.controlArea, "Colors")
        self.colormap_cb = gui.comboBox(box,
                                        self,
                                        "colormap",
                                        callback=self._update_color)
        self.colormap_cb.setIconSize(QSize(64, 16))
        self.palettes = list(_color_palettes)

        init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16))
        self.colormap_cb.setCurrentIndex(self.colormap)

        form = QFormLayout(formAlignment=Qt.AlignLeft,
                           labelAlignment=Qt.AlignLeft,
                           fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        #         form.addRow(
        #             "Gamma",
        #             gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0,
        #                         step=0.05, ticks=True, intOnly=False,
        #                         createLabel=False, callback=self._update_color)
        #         )
        form.addRow(
            "Low",
            gui.hSlider(box,
                        self,
                        "color_low",
                        minValue=0.0,
                        maxValue=1.0,
                        step=0.05,
                        ticks=True,
                        intOnly=False,
                        createLabel=False,
                        callback=self._update_color))
        form.addRow(
            "High",
            gui.hSlider(box,
                        self,
                        "color_high",
                        minValue=0.0,
                        maxValue=1.0,
                        step=0.05,
                        ticks=True,
                        intOnly=False,
                        createLabel=False,
                        callback=self._update_color))
        box.layout().addLayout(form)

        self.annot_combo = gui.comboBox(self.controlArea,
                                        self,
                                        "annotation_idx",
                                        box="Annotations",
                                        callback=self._invalidate_annotations,
                                        contentsLength=12)
        self.annot_combo.setModel(itemmodels.VariableListModel())
        self.annot_combo.model()[:] = ["None", "Enumeration"]
        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "autocommit", "Send data",
                        "Auto send is on")

        self.view = pg.GraphicsView(background="w")
        self.mainArea.layout().addWidget(self.view)

        self.grid_widget = pg.GraphicsWidget()
        self.grid = QGraphicsGridLayout()
        self.grid_widget.setLayout(self.grid)

        self.viewbox = pg.ViewBox(enableMouse=False, enableMenu=False)
        self.viewbox.setAcceptedMouseButtons(Qt.NoButton)
        self.viewbox.setAcceptHoverEvents(False)
        self.grid.addItem(self.viewbox, 1, 1)

        self.left_dendrogram = DendrogramWidget(
            self.grid_widget,
            orientation=DendrogramWidget.Left,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False)
        self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.left_dendrogram.setAcceptHoverEvents(False)

        self.top_dendrogram = DendrogramWidget(
            self.grid_widget,
            orientation=DendrogramWidget.Top,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False)
        self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.top_dendrogram.setAcceptHoverEvents(False)

        self.grid.addItem(self.left_dendrogram, 1, 0)
        self.grid.addItem(self.top_dendrogram, 0, 1)

        self.right_labels = TextList(alignment=Qt.AlignLeft)

        self.bottom_labels = TextList(orientation=Qt.Horizontal,
                                      alignment=Qt.AlignRight)

        self.grid.addItem(self.right_labels, 1, 2)
        self.grid.addItem(self.bottom_labels, 2, 1)

        self.view.setCentralItem(self.grid_widget)

        self.left_dendrogram.hide()
        self.top_dendrogram.hide()
        self.right_labels.hide()
        self.bottom_labels.hide()

        self.matrix_item = None
        self.dendrogram = None

        self.grid_widget.scene().installEventFilter(self)
Exemplo n.º 27
0
 def add_help(self):
     #Load help
     fileItem = QListWidgetItem(QIcon(resources.IMAGES['locate-file']),
                                '@\t(Filter only by Files)')
     font = fileItem.font()
     font.setBold(True)
     fileItem.setSizeHint(QSize(20, 30))
     fileItem.setBackground(QBrush(Qt.lightGray))
     fileItem.setForeground(QBrush(Qt.black))
     fileItem.setFont(font)
     self.listWidget.addItem(fileItem)
     classItem = QListWidgetItem(QIcon(resources.IMAGES['locate-class']),
                                 '<\t(Filter only by Classes)')
     self.listWidget.addItem(classItem)
     classItem.setSizeHint(QSize(20, 30))
     classItem.setBackground(QBrush(Qt.lightGray))
     classItem.setForeground(QBrush(Qt.black))
     classItem.setFont(font)
     methodItem = QListWidgetItem(
         QIcon(resources.IMAGES['locate-function']),
         '>\t(Filter only by Methods)')
     self.listWidget.addItem(methodItem)
     methodItem.setSizeHint(QSize(20, 30))
     methodItem.setBackground(QBrush(Qt.lightGray))
     methodItem.setForeground(QBrush(Qt.black))
     methodItem.setFont(font)
     attributeItem = QListWidgetItem(
         QIcon(resources.IMAGES['locate-attributes']),
         '-\t(Filter only by Attributes)')
     self.listWidget.addItem(attributeItem)
     attributeItem.setSizeHint(QSize(20, 30))
     attributeItem.setBackground(QBrush(Qt.lightGray))
     attributeItem.setForeground(QBrush(Qt.black))
     attributeItem.setFont(font)
     thisFileItem = QListWidgetItem(
         QIcon(resources.IMAGES['locate-on-this-file']),
         '.\t(Filter only by Classes and Methods in this File)')
     font = thisFileItem.font()
     font.setBold(True)
     thisFileItem.setSizeHint(QSize(20, 30))
     thisFileItem.setBackground(QBrush(Qt.lightGray))
     thisFileItem.setForeground(QBrush(Qt.black))
     thisFileItem.setFont(font)
     self.listWidget.addItem(thisFileItem)
     tabsItem = QListWidgetItem(QIcon(resources.IMAGES['locate-tab']),
                                '/\t(Filter only by the current Tabs)')
     font = tabsItem.font()
     font.setBold(True)
     tabsItem.setSizeHint(QSize(20, 30))
     tabsItem.setBackground(QBrush(Qt.lightGray))
     tabsItem.setForeground(QBrush(Qt.black))
     tabsItem.setFont(font)
     self.listWidget.addItem(tabsItem)
     lineItem = QListWidgetItem(QIcon(resources.IMAGES['locate-line']),
                                ':\t(Go to Line)')
     font = lineItem.font()
     font.setBold(True)
     lineItem.setSizeHint(QSize(20, 30))
     lineItem.setBackground(QBrush(Qt.lightGray))
     lineItem.setForeground(QBrush(Qt.black))
     lineItem.setFont(font)
     self.listWidget.addItem(lineItem)
     nonPythonItem = QListWidgetItem(
         QIcon(resources.IMAGES['locate-nonpython']),
         '!\t(Filter only by Non Python Files)')
     self.listWidget.addItem(nonPythonItem)
     nonPythonItem.setSizeHint(QSize(20, 30))
     nonPythonItem.setBackground(QBrush(Qt.lightGray))
     nonPythonItem.setForeground(QBrush(Qt.black))
     nonPythonItem.setFont(font)
Exemplo n.º 28
0
 def sizeHint(self):
     sh = super().sizeHint()
     return sh.expandedTo(QSize(1200, 800))
Exemplo n.º 29
0
 def sizeHint(self):
     w, h = self.get_width_height()
     return QSize(w, h)
Exemplo n.º 30
0
def load(filename, widget):
    """Loads snippets from a file, displaying them in a list.
    
    The user can then choose:
    - overwrite builtin snippets or not
    - overwrite own snippets with same title or not
    - select and view snippets contents.
    
    """
    try:
        d = ET.parse(filename)
        elements = list(d.findall('snippet'))
        if not elements:
            raise ValueError(_("No snippets found."))
    except Exception as e:
        QMessageBox.critical(
            widget, app.caption(_("Error")),
            _("Can't read from source:\n\n{url}\n\n{error}").format(
                url=filename, error=e))
        return

    dlg = widgets.dialog.Dialog(widget)
    dlg.setWindowModality(Qt.WindowModal)
    dlg.setWindowTitle(app.caption(_("dialog title", "Import Snippets")))
    tree = QTreeWidget(headerHidden=True, rootIsDecorated=False)
    dlg.setMainWidget(tree)
    userguide.addButton(dlg.buttonBox(), "snippet_import_export")

    allnames = frozenset(snippets.names())
    builtins = frozenset(builtin.builtin_snippets)
    titles = dict(
        (snippets.title(n), n) for n in allnames if n not in builtins)

    new = QTreeWidgetItem(tree, [_("New Snippets")])
    updated = QTreeWidgetItem(tree, [_("Updated Snippets")])
    unchanged = QTreeWidgetItem(tree, [_("Unchanged Snippets")])

    new.setFlags(Qt.ItemIsEnabled)
    updated.setFlags(Qt.ItemIsEnabled)
    unchanged.setFlags(Qt.ItemIsEnabled)

    new.setExpanded(True)
    updated.setExpanded(True)

    items = []
    for snip in elements:
        item = QTreeWidgetItem()

        item.body = snip.find('body').text
        item.title = snip.find('title').text
        item.shortcuts = list(e.text
                              for e in snip.findall('shortcuts/shortcut'))

        title = item.title or snippets.maketitle(
            snippets.parse(item.body).text)
        item.setText(0, title)

        name = snip.get('id')
        name = name if name in builtins else None

        # determine if new, updated or unchanged
        if not name:
            name = titles.get(title)
        item.name = name

        if not name or name not in allnames:
            new.addChild(item)
            items.append(item)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
            item.setCheckState(0, Qt.Checked)
        elif name:
            if (item.body != snippets.text(name)
                    or title != snippets.title(name)
                    or (item.shortcuts and item.shortcuts !=
                        [s.toString() for s in model.shortcuts(name) or ()])):
                updated.addChild(item)
                items.append(item)
                item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
                item.setCheckState(0, Qt.Checked)
            else:
                unchanged.addChild(item)
                item.setFlags(Qt.ItemIsEnabled)
    # count:
    for i in new, updated, unchanged:
        i.setText(0, i.text(0) + " ({0})".format(i.childCount()))
    for i in new, updated:
        if i.childCount():
            i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
            i.setCheckState(0, Qt.Checked)

    def changed(item):
        if item in (new, updated):
            for i in range(item.childCount()):
                c = item.child(i)
                c.setCheckState(0, item.checkState(0))

    tree.itemChanged.connect(changed)

    importShortcuts = QTreeWidgetItem([_("Import Keyboard Shortcuts")])
    if items:
        tree.addTopLevelItem(importShortcuts)
        importShortcuts.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
        importShortcuts.setCheckState(0, Qt.Checked)
        dlg.setMessage(_("Choose which snippets you want to import:"))
    else:
        dlg.setMessage(_("There are no new or updated snippets in the file."))
        unchanged.setExpanded(True)

    tree.setWhatsThis(
        _("<p>Here the snippets from {filename} are displayed.</p>\n"
          "<p>If there are new or updated snippets, you can select or deselect "
          "them one by one, or all at once, using the checkbox of the group. "
          "Then click OK to import all the selected snippets.</p>\n"
          "<p>Existing, unchanged snippets can't be imported.</p>\n").format(
              filename=os.path.basename(filename)))

    qutil.saveDialogSize(dlg, "snippettool/import/size", QSize(400, 300))
    if not dlg.exec_() or not items:
        return
    ac = model.collection()
    m = model.model()
    with qutil.busyCursor():
        for i in items:
            if i.checkState(0) == Qt.Checked:
                index = m.saveSnippet(i.name, i.body, i.title)
                if i.shortcuts and importShortcuts.checkState(0):
                    shortcuts = list(map(QKeySequence.fromString, i.shortcuts))
                    ac.setShortcuts(m.name(index), shortcuts)
        widget.updateColumnSizes()