Ejemplo n.º 1
0
    def _createToolButtonWidget(self, parent):
        """
        @see: self.createWidget()
        """
        btn = QToolButton(parent)
        btn.setAutoFillBackground(True)
        btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        btn.setMinimumWidth(75)
        btn.setMaximumWidth(75)
        btn.setMinimumHeight(62)
        btn.setAutoRaise(True)

        btn.setCheckable(True)
        btn.setDefaultAction(self)

        text = truncateText(self.text())
        btn.setText(text)

        if self._toolButtonPalette:
            btn.setPalette(self._toolButtonPalette)

        #@@@ ninad070125 The following function
        #adds a newline character after each word in toolbutton text.
        #but the changes are reflected only on 'mode' toolbuttons
        #on the flyout toolbar (i.e.only Checkable buttons..don't know
        #why. Disabling its use for now.
        debug_wrapText = False

        if debug_wrapText:
            text = wrapToolButtonText(action.text())
            if text:
                action.setText(text)

        return btn
Ejemplo n.º 2
0
 def makeButton(self, label, callback=None, width=None, icon=None):
     btn = QToolButton(self)
     #    btn.setAutoRaise(True)
     label and btn.setText(label)
     icon and btn.setIcon(icon)
     #    btn = QPushButton(label,self)
     #   btn.setFlat(True)
     if width:
         btn.setMinimumWidth(width)
         btn.setMaximumWidth(width)
     if icon:
         btn.setIcon(icon)
     if callback:
         QObject.connect(btn, SIGNAL("clicked()"), callback)
     return btn
Ejemplo n.º 3
0
class StatusBar(QStatusBar):
    def __init__(self, win):
        QStatusBar.__init__(self, win)
        self._progressLabel = QLabel()

        self._progressLabel.setMinimumWidth(200)
        self._progressLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.addPermanentWidget(self._progressLabel)

        self.progressBar = QProgressBar(win)
        self.progressBar.setMaximumWidth(250)
        qt4todo('StatusBar.progressBar.setCenterIndicator(True)')
        self.addPermanentWidget(self.progressBar)
        self.progressBar.hide()

        self.simAbortButton = QToolButton(win)
        self.simAbortButton.setIcon(
            geticon("ui/actions/Simulation/Stopsign.png"))
        self.simAbortButton.setMaximumWidth(32)
        self.addPermanentWidget(self.simAbortButton)
        self.connect(self.simAbortButton, SIGNAL("clicked()"), self.simAbort)
        self.simAbortButton.hide()

        self.dispbarLabel = QLabel(win)
        #self.dispbarLabel.setFrameStyle( QFrame.Panel | QFrame.Sunken )
        self.dispbarLabel.setText("Global display style:")
        self.addPermanentWidget(self.dispbarLabel)

        # Global display styles combobox
        self.globalDisplayStylesComboBox = GlobalDisplayStylesComboBox(win)
        self.addPermanentWidget(self.globalDisplayStylesComboBox)

        # Selection lock button. It always displays the selection lock state
        # and it is available to click.
        self.selectionLockButton = QToolButton(win)
        self.selectionLockButton.setDefaultAction(win.selectLockAction)
        self.addPermanentWidget(self.selectionLockButton)

        self.abortableCommands = {}

        #bruce 081230 debug code:
        ## self.connect(self, SIGNAL('messageChanged ( const QString &)'),
        ##              self.slotMessageChanged )


##     def slotMessageChanged(self, message): # bruce 081230 debug code
##         print "messageChanged: %r" % str(message)

    def showMessage(self, text):  #bruce 081230
        """
        [extends superclass method]
        """
        ## QStatusBar.showMessage(self, " ")
        QStatusBar.showMessage(self, text)
        ## print "message was set to %r" % str(self.currentMessage())
        return

    def _f_progress_msg(self, text):  #bruce 081229 refactoring
        """
        Friend method for use only by present implementation
        of env.history.progress_msg. Display text in our
        private label widget dedicated to progress messages.
        """
        self._progressLabel.setText(text)
        return

    def makeCommandNameUnique(self, commandName):
        index = 1
        trial = commandName
        while (self.abortableCommands.has_key(trial)):
            trial = "%s [%d]" % (commandName, index)
            index += 1
        return trial

    def addAbortableCommand(self, commandName, abortHandler):
        uniqueCommandName = self.makeCommandNameUnique(commandName)
        self.abortableCommands[uniqueCommandName] = abortHandler
        return uniqueCommandName

    def removeAbortableCommand(self, commandName):
        del self.abortableCommands[commandName]

    def simAbort(self):
        """
        Slot for Abort button.
        """
        if debug_flags.atom_debug and self.sim_abort_button_pressed:  #bruce 060106
            print "atom_debug: self.sim_abort_button_pressed is already True before we even put up our dialog"

        # Added confirmation before aborting as part of fix to bug 915. Mark 050824.
        # Bug 915 had to do with a problem if the user accidently hit the space bar or espace key,
        # which would call this slot and abort the simulation.  This should no longer be an issue here
        # since we aren't using a dialog.  I still like having this confirmation anyway.
        # IMHO, it should be kept. Mark 060106.
        ret = QMessageBox.warning(
            self,
            "Confirm",
            "Please confirm you want to abort.\n",
            "Confirm",
            "Cancel",
            "",
            1,  # The "default" button, when user presses Enter or Return (1 = Cancel)
            1)  # Escape (1= Cancel)

        if ret == 0:  # Confirmed
            for abortHandler in self.abortableCommands.values():
                abortHandler.pressed()

    def show_indeterminate_progress(self):
        value = self.progressBar.value()
        self.progressBar.setValue(value)

    def possibly_hide_progressbar_and_stop_button(self):
        if (len(self.abortableCommands) <= 0):
            self.progressBar.reset()
            self.progressBar.hide()
            self.simAbortButton.hide()

    def show_progressbar_and_stop_button(self,
                                         progressReporter,
                                         cmdname="<unknown command>",
                                         showElapsedTime=False):
        """
        Display the statusbar's progressbar and stop button, and
        update it based on calls to the progressReporter.

        When the progressReporter indicates completion, hide the
        progressbar and stop button and return 0. If the user first
        presses the Stop button on the statusbar, hide the progressbar
        and stop button and return 1.

        Parameters:
        progressReporter - See potential implementations below.
        cmdname - name of command (used in some messages and in abort button tooltip)
        showElapsedTime - if True, display duration (in seconds) below progress bar

        Return value: 0 if file reached desired size, 1 if user hit abort button.

        """

        updateInterval = .1  # seconds
        startTime = time.time()
        elapsedTime = 0
        displayedElapsedTime = 0

        ###e the following is WRONG if there is more than one task at a time... [bruce 060106 comment]
        self.progressBar.reset()
        self.progressBar.setMaximum(progressReporter.getMaxProgress())
        self.progressBar.setValue(0)
        self.progressBar.show()

        abortHandler = AbortHandler(self, cmdname)

        # Main loop
        while progressReporter.notDoneYet():
            self.progressBar.setValue(progressReporter.getProgress())
            env.call_qApp_processEvents()
            # Process queued events (e.g. clicking Abort button,
            # but could be anything -- no modal dialog involved anymore).

            if showElapsedTime:
                elapsedTime = int(time.time() - startTime)
                if (elapsedTime != displayedElapsedTime):
                    displayedElapsedTime = elapsedTime
                    env.history.progress_msg("Elapsed Time: " +
                                             hhmmss_str(displayedElapsedTime))
                    # note: it's intentional that this doesn't directly call
                    # self._f_progress_msg. [bruce 081229 comment]

            if abortHandler.getPressCount() > 0:
                env.history.statusbar_msg("Aborted.")
                abortHandler.finish()
                return 1

            time.sleep(updateInterval)  # Take a rest

        # End of Main loop (this only runs if it ended without being aborted)
        self.progressBar.setValue(progressReporter.getMaxProgress())
        time.sleep(
            updateInterval)  # Give the progress bar a moment to show 100%
        env.history.statusbar_msg("Done.")
        abortHandler.finish()
        return 0
Ejemplo n.º 4
0
class StatusBar(QStatusBar):
    def __init__(self, win):
        QStatusBar.__init__(self, win)
        self.statusMsgLabel = QLabel()

        self.statusMsgLabel.setMinimumWidth(200)
        self.statusMsgLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.addPermanentWidget(self.statusMsgLabel)

        self.progressBar = QProgressBar(win)
        self.progressBar.setMaximumWidth(250)
        qt4todo("StatusBar.progressBar.setCenterIndicator(True)")
        self.addPermanentWidget(self.progressBar)
        self.progressBar.hide()

        self.simAbortButton = QToolButton(win)
        self.simAbortButton.setIcon(geticon("ui/actions/Simulation/Stopsign.png"))
        self.simAbortButton.setMaximumWidth(32)
        self.addPermanentWidget(self.simAbortButton)
        self.connect(self.simAbortButton, SIGNAL("clicked()"), self.simAbort)
        self.simAbortButton.hide()

        self.dispbarLabel = QLabel(win)
        # self.dispbarLabel.setFrameStyle( QFrame.Panel | QFrame.Sunken )
        self.dispbarLabel.setText("Global display style:")
        self.addPermanentWidget(self.dispbarLabel)

        # Global display styles combobox
        self.globalDisplayStylesComboBox = GlobalDisplayStylesComboBox(win)
        self.addPermanentWidget(self.globalDisplayStylesComboBox)

        # Selection lock button. It always displays the selection lock state
        # and it is available to click.
        self.selectionLockButton = QToolButton(win)
        self.selectionLockButton.setDefaultAction(win.selectLockAction)
        self.addPermanentWidget(self.selectionLockButton)

        # Only use of this appears to be commented out in MWsemantics as of 2007/12/14
        self.modebarLabel = QLabel(win)
        self.addPermanentWidget(self.modebarLabel)
        self.abortableCommands = {}

    def makeCommandNameUnique(self, commandName):
        index = 1
        trial = commandName
        while self.abortableCommands.has_key(trial):
            trial = "%s [%d]" % (commandName, index)
            index += 1
        return trial

    def addAbortableCommand(self, commandName, abortHandler):
        uniqueCommandName = self.makeCommandNameUnique(commandName)
        self.abortableCommands[uniqueCommandName] = abortHandler
        return uniqueCommandName

    def removeAbortableCommand(self, commandName):
        del self.abortableCommands[commandName]

    def simAbort(self):
        """
        Slot for Abort button.
        """
        if debug_flags.atom_debug and self.sim_abort_button_pressed:  # bruce 060106
            print "atom_debug: self.sim_abort_button_pressed is already True before we even put up our dialog"

        # Added confirmation before aborting as part of fix to bug 915. Mark 050824.
        # Bug 915 had to do with a problem if the user accidently hit the space bar or espace key,
        # which would call this slot and abort the simulation.  This should no longer be an issue here
        # since we aren't using a dialog.  I still like having this confirmation anyway.
        # IMHO, it should be kept. Mark 060106.
        ret = QMessageBox.warning(
            self,
            "Confirm",
            "Please confirm you want to abort.\n",
            "Confirm",
            "Cancel",
            "",
            1,  # The "default" button, when user presses Enter or Return (1 = Cancel)
            1,
        )  # Escape (1= Cancel)

        if ret == 0:  # Confirmed
            for abortHandler in self.abortableCommands.values():
                abortHandler.pressed()

    def show_indeterminate_progress(self):
        value = self.progressBar.value()
        self.progressBar.setValue(value)

    def possibly_hide_progressbar_and_stop_button(self):
        if len(self.abortableCommands) <= 0:
            self.progressBar.reset()
            self.progressBar.hide()
            self.simAbortButton.hide()

    def show_progressbar_and_stop_button(self, progressReporter, cmdname="<unknown command>", showElapsedTime=False):
        """
        Display the statusbar's progressbar and stop button, and
        update it based on calls to the progressReporter.

        When the progressReporter indicates completion, hide the
        progressbar and stop button and return 0. If the user first
        presses the Stop button on the statusbar, hide the progressbar
        and stop button and return 1.

        Parameters:
        progressReporter - See potential implementations below.
        cmdname - name of command (used in some messages and in abort button tooltip)
        showElapsedTime - if True, display duration (in seconds) below progress bar

        Return value: 0 if file reached desired size, 1 if user hit abort button.

        """

        updateInterval = 0.1  # seconds
        startTime = time.time()
        elapsedTime = 0
        displayedElapsedTime = 0

        ###e the following is WRONG if there is more than one task at a time... [bruce 060106 comment]
        self.progressBar.reset()
        self.progressBar.setMaximum(progressReporter.getMaxProgress())
        self.progressBar.setValue(0)
        self.progressBar.show()

        abortHandler = AbortHandler(self, cmdname)

        # Main loop
        while progressReporter.notDoneYet():
            self.progressBar.setValue(progressReporter.getProgress())
            env.call_qApp_processEvents()
            # Process queued events (e.g. clicking Abort button,
            # but could be anything -- no modal dialog involved anymore).

            if showElapsedTime:
                elapsedTime = int(time.time() - startTime)
                if elapsedTime != displayedElapsedTime:
                    displayedElapsedTime = elapsedTime
                    env.history.progress_msg("Elapsed Time: " + hhmmss_str(displayedElapsedTime))

            if abortHandler.getPressCount() > 0:
                env.history.statusbar_msg("Aborted.")
                abortHandler.finish()
                return 1

            time.sleep(updateInterval)  # Take a rest

        # End of Main loop (this only runs if it ended without being aborted)
        self.progressBar.setValue(progressReporter.getMaxProgress())
        time.sleep(updateInterval)  # Give the progress bar a moment to show 100%
        env.history.statusbar_msg("Done.")
        abortHandler.finish()
        return 0
Ejemplo n.º 5
0
 def _updateModel(self, what=SkyModel.UpdateAll, origin=None):
     if origin is self or not what & (SkyModel.UpdateTags
                                      | SkyModel.UpdateGroupStyle):
         return
     model = self.model
     self._setting_model = True
     # to ignore cellChanged() signals (in valueChanged())
     # _item_cb is a dict (with row,col keys) containing the widgets (CheckBoxes ComboBoxes) per each cell
     self._item_cb = {}
     # lists of "list" and "plot" checkboxes per each grouping (excepting the default grouping); each entry is an (row,col,item) tuple.
     # used as argument to self._showControls()
     self._list_controls = []
     self._plot_controls = []
     # list of selection callbacks (to which signals are connected)
     self._callbacks = []
     # set requisite number of rows,and start filling
     self.table.setRowCount(len(model.groupings))
     for irow, group in enumerate(model.groupings):
         self.table.setItem(irow, 0, QTableWidgetItem(group.name))
         if group is model.selgroup:
             self._irow_selgroup = irow
         # total # source in group: skip for "current"
         if group is not model.curgroup:
             self.table.setItem(irow, 1, QTableWidgetItem(str(group.total)))
         # selection controls: skip for current and selection
         if group not in (model.curgroup, model.selgroup):
             btns = QWidget()
             lo = QHBoxLayout(btns)
             lo.setContentsMargins(0, 0, 0, 0)
             lo.setSpacing(0)
             # make selector buttons (depending on which group we're in)
             if group is model.defgroup:
                 Buttons = (("+", lambda src, grp=group: True,
                             "select all sources"),
                            ("-", lambda src, grp=group: False,
                             "unselect all sources"))
             else:
                 Buttons = (
                     ("=", lambda src, grp=group: grp.func(src),
                      "select only this grouping"),
                     ("+",
                      lambda src, grp=group: src.selected or grp.func(src),
                      "add grouping to selection"),
                     ("-", lambda src, grp=group: src.selected and not grp.
                      func(src), "remove grouping from selection"),
                     ("&&",
                      lambda src, grp=group: src.selected and grp.func(src),
                      "intersect selection with grouping"))
             lo.addStretch(1)
             for label, predicate, tooltip in Buttons:
                 btn = QToolButton(btns)
                 btn.setText(label)
                 btn.setMinimumWidth(24)
                 btn.setMaximumWidth(24)
                 btn.setToolTip(tooltip)
                 lo.addWidget(btn)
                 # add callback
                 QObject.connect(
                     btn, SIGNAL("clicked()"),
                     self._currier.curry(self.selectSources, predicate))
             lo.addStretch(1)
             self.table.setCellWidget(irow, 2, btns)
         # "list" checkbox (not for current and selected groupings: these are always listed)
         if group not in (model.curgroup, model.selgroup):
             item = self._makeCheckItem("", group, "show_list")
             self.table.setItem(irow, self.ColList, item)
             item.setToolTip(
                 """<P>If checked, sources in this grouping will be listed in the source table. If un-checked, sources will be
         excluded from the table. If partially checked, then the default list/no list setting of "all sources" will be in effect.
         </P>""")
         # "plot" checkbox (not for the current grouping, since that's always plotted)
         if group is not model.curgroup:
             item = self._makeCheckItem("", group, "show_plot")
             self.table.setItem(irow, self.ColPlot, item)
             item.setToolTip(
                 """<P>If checked, sources in this grouping will be included in the plot. If un-checked, sources will be
         excluded from the plot. If partially checked, then the default plot/no plot setting of "all sources" will be in effect.
         </P>""")
         # custom style control
         # for default, current and selected, this is just a text label
         if group is model.defgroup:
             item = QTableWidgetItem("default:")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the default plot style used for all sources for which a custom grouping style is not selected.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.curgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the plot style used for the highlighted source, if any.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.selgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the plot style used for the currently selected sources.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         # for the rest, a combobox with custom priorities
         else:
             cb = QComboBox()
             cb.addItems(["default"] +
                         ["custom %d" % p for p in range(1, 10)])
             index = max(0, min(group.style.apply, 9))
             #        dprint(0,group.name,"apply",index)
             cb.setCurrentIndex(index)
             QObject.connect(
                 cb, SIGNAL("activated(int)"),
                 self._currier.xcurry(self._valueChanged,
                                      (irow, self.ColApply)))
             self.table.setCellWidget(irow, self.ColApply, cb)
             cb.setToolTip(
                 """<P>This controls whether sources within this group are plotted with a customized
         plot style. Customized styles have numeric priority; if a source belongs to multiple groups, then
         the style with the lowest priority takes precedence.<P>""")
         # attribute comboboxes
         for icol, attr in self.AttrByCol.items():
             # get list of options for this style attribute. If dealing with first grouping (i==0), which is
             # the "all sources" grouping, then remove the "default" option (which is always first in the list)
             options = PlotStyles.StyleAttributeOptions[attr]
             if irow == 0:
                 options = options[1:]
             # make combobox
             cb = QComboBox()
             cb.addItems(list(map(str, options)))
             # the "label" option is also editable
             if attr == "label":
                 cb.setEditable(True)
             try:
                 index = options.index(getattr(group.style, attr))
                 cb.setCurrentIndex(index)
             except ValueError:
                 cb.setEditText(str(getattr(group.style, attr)))
             slot = self._currier.xcurry(self._valueChanged, (irow, icol))
             QObject.connect(cb, SIGNAL("activated(int)"), slot)
             QObject.connect(cb, SIGNAL("editTextChanged(const QString &)"),
                             slot)
             cb.setEnabled(group is model.defgroup or group.style.apply)
             self.table.setCellWidget(irow, icol, cb)
             label = attr
             if irow:
                 cb.setToolTip(
                     """<P>This is the %s used to plot sources in this group, when a "custom" style for the group
       is enabled via the style control.<P>""" % label)
             else:
                 cb.setToolTip(
                     "<P>This is the default %s used for all sources for which a custom style is not specified below.<P>"
                     % label)
     self.table.resizeColumnsToContents()
     # re-enable processing of cellChanged() signals
     self._setting_model = False
Ejemplo n.º 6
0
 def setupUi(self):
     """
     Setup the UI for the command toolbar.
     """
     #ninad 070123 : It's important to set the Vertical size policy of the 
     # cmd toolbar widget. otherwise the flyout QToolbar messes up the 
     #layout (makes the command toolbar twice as big) 
     #I have set the vertical policy as fixed. Works fine. There are some 
     # MainWindow resizing problems for but those are not due to this 
     #size policy AFAIK        
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
             
     layout_cmdtoolbar = QHBoxLayout(self)
     layout_cmdtoolbar.setMargin(2)
     layout_cmdtoolbar.setSpacing(2)
     
     #See comment at the top for details about this flag
     if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
         self.cmdToolbarControlArea = QWidget(self)    
     else:
         self.cmdToolbarControlArea = QToolBar_WikiHelp(self)
         
     self.cmdToolbarControlArea.setAutoFillBackground(True)
             
     self.ctrlAreaPalette = self.getCmdMgrCtrlAreaPalette()  
     self.cmdToolbarControlArea.setPalette(self.ctrlAreaPalette)
             
     self.cmdToolbarControlArea.setMinimumHeight(62)
     self.cmdToolbarControlArea.setMinimumWidth(380)
     self.cmdToolbarControlArea.setSizePolicy(QSizePolicy.Fixed, 
                                              QSizePolicy.Fixed)  
     
     #See comment at the top for details about this flag
     if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
         layout_controlArea = QHBoxLayout(self.cmdToolbarControlArea)
         layout_controlArea.setMargin(0)
         layout_controlArea.setSpacing(0)
     
     self.cmdButtonGroup = QButtonGroup()    
     btn_index = 0
     
     for name in ('Build', 'Insert', 'Tools', 'Move', 'Simulation'):
         btn = QToolButton(self.cmdToolbarControlArea)           
         btn.setObjectName(name)
         btn.setMinimumWidth(75)
         btn.setMaximumWidth(75)
         btn.setMinimumHeight(62)
         btn.setAutoRaise(True)
         btn.setCheckable(True)
         btn.setAutoExclusive(True)
         iconpath = "ui/actions/Command Toolbar/ControlArea/" + name + ".png"
         btn.setIcon(geticon(iconpath))
         btn.setIconSize(QSize(22, 22))
         btn.setText(name)
         btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
         btn.setPalette(self.ctrlAreaPalette)
         self.cmdButtonGroup.addButton(btn, btn_index)
         btn_index += 1        
         #See comment at the top for details about this flag
         if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
             layout_controlArea.addWidget(btn)
         else:
             self.cmdToolbarControlArea.layout().addWidget(btn)                
             #following has issues. so not adding widget directly to the 
             #toolbar. (instead adding it in its layout)-- ninad 070124
             ##self.cmdToolbarControlArea.addWidget(btn)      
     
     layout_cmdtoolbar.addWidget(self.cmdToolbarControlArea) 
     
     #Flyout Toolbar in the command toolbar  
     self.flyoutToolBar = FlyoutToolBar(self)
     
     layout_cmdtoolbar.addWidget(self.flyoutToolBar)   
     
     #ninad 070116: Define a spacer item. It will have the exact geometry 
     # as that of the flyout toolbar. it is added to the command toolbar 
     # layout only when the Flyout Toolbar is hidden. It is required
     # to keep the 'Control Area' widget fixed in its place (otherwise, 
     #after hiding the flyout toolbar, the layout adjusts the position of 
     #remaining widget items) 
     
     self.spacerItem = QSpacerItem(0, 
                                   0, 
                                   QtGui.QSizePolicy.Expanding, 
                                   QtGui.QSizePolicy.Minimum)
     self.spacerItem.setGeometry = self.flyoutToolBar.geometry()
     
     for btn in self.cmdButtonGroup.buttons():
         if str(btn.objectName()) == 'Build':
             btn.setMenu(self.win.buildStructuresMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Build Commands")
             whatsThisTextForCommandToolbarBuildButton(btn)
         if str(btn.objectName()) == 'Insert':
             btn.setMenu(self.win.insertMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Insert Commands")
             whatsThisTextForCommandToolbarInsertButton(btn)
         if str(btn.objectName()) == 'Tools':
             #fyi: cmd stands for 'command toolbar' - ninad070406
             self.win.cmdToolsMenu = QtGui.QMenu(self.win)
             self.win.cmdToolsMenu.addAction(self.win.toolsExtrudeAction) 
             self.win.cmdToolsMenu.addAction(self.win.toolsFuseChunksAction)
             self.win.cmdToolsMenu.addSeparator()
             self.win.cmdToolsMenu.addAction(self.win.modifyMergeAction)
             self.win.cmdToolsMenu.addAction(self.win.modifyMirrorAction)
             self.win.cmdToolsMenu.addAction(self.win.modifyInvertAction)
             self.win.cmdToolsMenu.addAction(self.win.modifyStretchAction)
             btn.setMenu(self.win.cmdToolsMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Tools")
             whatsThisTextForCommandToolbarToolsButton(btn)
         if str(btn.objectName()) == 'Move':
             self.win.moveMenu = QtGui.QMenu(self.win)
             self.win.moveMenu.addAction(self.win.toolsMoveMoleculeAction)
             self.win.moveMenu.addAction(self.win.rotateComponentsAction)
             self.win.moveMenu.addSeparator()
             self.win.moveMenu.addAction(
                 self.win.modifyAlignCommonAxisAction)
             ##self.win.moveMenu.addAction(\
             ##    self.win.modifyCenterCommonAxisAction)
             btn.setMenu(self.win.moveMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Move Commands")
             whatsThisTextForCommandToolbarMoveButton(btn)
         if str(btn.objectName()) == 'Dimension':
             btn.setMenu(self.win.dimensionsMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Dimensioning Commands")
         if str(btn.objectName()) == 'Simulation':
             btn.setMenu(self.win.simulationMenu)
             btn.setPopupMode(QToolButton.MenuButtonPopup)
             btn.setToolTip("Simulation Commands")
             whatsThisTextForCommandToolbarSimulationButton(btn)
         
         # Convert all "img" tags in the button's "What's This" text 
         # into abs paths (from their original rel paths).
         # Partially fixes bug 2943. --mark 2008-12-07
         # [bruce 081209 revised this -- removed mac = False]
         fix_QAction_whatsthis(btn)
     return
Ejemplo n.º 7
0
 def _updateModel(self, what=SkyModel.UpdateAll, origin=None):
     if origin is self or not what & (SkyModel.UpdateTags | SkyModel.UpdateGroupStyle):
         return
     model = self.model
     self._setting_model = True;  # to ignore cellChanged() signals (in valueChanged())
     # _item_cb is a dict (with row,col keys) containing the widgets (CheckBoxes ComboBoxes) per each cell
     self._item_cb = {}
     # lists of "list" and "plot" checkboxes per each grouping (excepting the default grouping); each entry is an (row,col,item) tuple.
     # used as argument to self._showControls()
     self._list_controls = []
     self._plot_controls = []
     # list of selection callbacks (to which signals are connected)
     self._callbacks = []
     # set requisite number of rows,and start filling
     self.table.setRowCount(len(model.groupings))
     for irow, group in enumerate(model.groupings):
         self.table.setItem(irow, 0, QTableWidgetItem(group.name))
         if group is model.selgroup:
             self._irow_selgroup = irow
         # total # source in group: skip for "current"
         if group is not model.curgroup:
             self.table.setItem(irow, 1, QTableWidgetItem(str(group.total)))
         # selection controls: skip for current and selection
         if group not in (model.curgroup, model.selgroup):
             btns = QWidget()
             lo = QHBoxLayout(btns)
             lo.setContentsMargins(0, 0, 0, 0)
             lo.setSpacing(0)
             # make selector buttons (depending on which group we're in)
             if group is model.defgroup:
                 Buttons = (
                     ("+", lambda src, grp=group: True, "select all sources"),
                     ("-", lambda src, grp=group: False, "unselect all sources"))
             else:
                 Buttons = (
                     ("=", lambda src, grp=group: grp.func(src), "select only this grouping"),
                     ("+", lambda src, grp=group: src.selected or grp.func(src), "add grouping to selection"),
                     ("-", lambda src, grp=group: src.selected and not grp.func(src),
                      "remove grouping from selection"),
                     ("&&", lambda src, grp=group: src.selected and grp.func(src),
                      "intersect selection with grouping"))
             lo.addStretch(1)
             for label, predicate, tooltip in Buttons:
                 btn = QToolButton(btns)
                 btn.setText(label)
                 btn.setMinimumWidth(24)
                 btn.setMaximumWidth(24)
                 btn.setToolTip(tooltip)
                 lo.addWidget(btn)
                 # add callback
                 QObject.connect(btn, SIGNAL("clicked()"), self._currier.curry(self.selectSources, predicate))
             lo.addStretch(1)
             self.table.setCellWidget(irow, 2, btns)
         # "list" checkbox (not for current and selected groupings: these are always listed)
         if group not in (model.curgroup, model.selgroup):
             item = self._makeCheckItem("", group, "show_list")
             self.table.setItem(irow, self.ColList, item)
             item.setToolTip("""<P>If checked, sources in this grouping will be listed in the source table. If un-checked, sources will be
         excluded from the table. If partially checked, then the default list/no list setting of "all sources" will be in effect.
         </P>""")
         # "plot" checkbox (not for the current grouping, since that's always plotted)
         if group is not model.curgroup:
             item = self._makeCheckItem("", group, "show_plot")
             self.table.setItem(irow, self.ColPlot, item)
             item.setToolTip("""<P>If checked, sources in this grouping will be included in the plot. If un-checked, sources will be
         excluded from the plot. If partially checked, then the default plot/no plot setting of "all sources" will be in effect.
         </P>""")
         # custom style control
         # for default, current and selected, this is just a text label
         if group is model.defgroup:
             item = QTableWidgetItem("default:")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the default plot style used for all sources for which a custom grouping style is not selected.</P>""")
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.curgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip("""<P>This is the plot style used for the highlighted source, if any.</P>""")
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.selgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip("""<P>This is the plot style used for the currently selected sources.</P>""")
             self.table.setItem(irow, self.ColApply, item)
         # for the rest, a combobox with custom priorities
         else:
             cb = QComboBox()
             cb.addItems(["default"] + ["custom %d" % p for p in range(1, 10)])
             index = max(0, min(group.style.apply, 9))
             #        dprint(0,group.name,"apply",index)
             cb.setCurrentIndex(index)
             QObject.connect(cb, SIGNAL("activated(int)"),
                             self._currier.xcurry(self._valueChanged, (irow, self.ColApply)))
             self.table.setCellWidget(irow, self.ColApply, cb)
             cb.setToolTip("""<P>This controls whether sources within this group are plotted with a customized
         plot style. Customized styles have numeric priority; if a source belongs to multiple groups, then
         the style with the lowest priority takes precedence.<P>""")
         # attribute comboboxes
         for icol, attr in self.AttrByCol.items():
             # get list of options for this style attribute. If dealing with first grouping (i==0), which is
             # the "all sources" grouping, then remove the "default" option (which is always first in the list)
             options = PlotStyles.StyleAttributeOptions[attr]
             if irow == 0:
                 options = options[1:]
             # make combobox
             cb = QComboBox()
             cb.addItems(list(map(str, options)))
             # the "label" option is also editable
             if attr == "label":
                 cb.setEditable(True)
             try:
                 index = options.index(getattr(group.style, attr))
                 cb.setCurrentIndex(index)
             except ValueError:
                 cb.setEditText(str(getattr(group.style, attr)))
             slot = self._currier.xcurry(self._valueChanged, (irow, icol))
             QObject.connect(cb, SIGNAL("activated(int)"), slot)
             QObject.connect(cb, SIGNAL("editTextChanged(const QString &)"), slot)
             cb.setEnabled(group is model.defgroup or group.style.apply)
             self.table.setCellWidget(irow, icol, cb)
             label = attr
             if irow:
                 cb.setToolTip("""<P>This is the %s used to plot sources in this group, when a "custom" style for the group
       is enabled via the style control.<P>""" % label)
             else:
                 cb.setToolTip(
                     "<P>This is the default %s used for all sources for which a custom style is not specified below.<P>" % label)
     self.table.resizeColumnsToContents()
     # re-enable processing of cellChanged() signals
     self._setting_model = False
Ejemplo n.º 8
0
class GAppLayerW(QgsMapCanvas):
    def __init__(self, layer, rawLayer, linkedCanvas, dock):

        # Canvas params
        QgsMapCanvas.__init__(self, dock)
        self.setCanvasColor(Qt.white)
        self.setWheelAction(QgsMapCanvas.WheelZoom, factor=0)
        self._dock = dock

        # Add buttons
        buttonWidth = self.width() / 2.5

        self._buttonUp = QToolButton(self)
        self._buttonUp.setArrowType(Qt.UpArrow)
        self._buttonUp.setMaximumWidth(buttonWidth)
        self._buttonUp.setVisible(False)
        self._buttonUp.connect(self._buttonUp, SIGNAL("clicked()"),
                               self.moveUp)

        self._buttonHide = QPushButton("Hide")
        self._buttonHide.setMaximumWidth(buttonWidth)
        self._buttonHide.setVisible(False)
        self._buttonHide.setFocusPolicy(Qt.NoFocus)
        self._buttonHide.connect(self._buttonHide, SIGNAL("clicked()"),
                                 self.toggleLayer)

        self._buttonDown = QToolButton(self)
        self._buttonDown.setArrowType(Qt.DownArrow)
        self._buttonDown.setMaximumWidth(buttonWidth)
        self._buttonDown.setVisible(False)
        self._buttonDown.connect(self._buttonDown, SIGNAL("clicked()"),
                                 self.moveDown)

        self._layout = QVBoxLayout(self)
        self._layout.setMargin(1)
        self._layout.addWidget(self._buttonUp)
        self._layout.addWidget(self._buttonHide)
        self._layout.addWidget(self._buttonDown)

        self._rawLayer = rawLayer

        self._layer = layer
        self.setLayerSet([layer])

        self._linkedCanvas = linkedCanvas
        self._extent = self._linkedCanvas.extent()

        self.setExtent(self._extent)

        self.setFocusPolicy(Qt.StrongFocus)
        self._hidden = False

    def toggleLayer(self):
        if not self._hidden:
            self._linkedCanvas.hideLayer(self._layer)
            self._buttonHide.setText("Show")
            self._hidden = True
        else:
            self._linkedCanvas.showLayer(self._layer)
            self._buttonHide.setText("Hide")
            self._hidden = False

    def moveUp(self):
        if not self._hidden:
            self._linkedCanvas.moveLayerUp(self._layer)
            self._dock.moveWidgetUp(self)

    def moveDown(self):
        if not self._hidden:
            self._linkedCanvas.moveLayerDown(self._layer)
            self._dock.moveWidgetDown(self)

    def refreshExtent(self):
        self._extent = self._linkedCanvas.extent()
        self.zoomToFeatureExtent(self._extent)

    def isCurrentLayer(self):
        return self._linkedCanvas.currentLayer == self._rawLayer

    def setAsCurrentLayer(self):
        self._linkedCanvas.setCurrentLayer(self._rawLayer)

    def focusInEvent(self, focusEvent):
        self._buttonUp.setVisible(True)
        self._buttonHide.setVisible(True)
        self._buttonDown.setVisible(True)

        # if not self.isCurrentLayer():
        #     self.setAsCurrentLayer()

        QgsMapCanvas.focusInEvent(self, focusEvent)

    def focusOutEvent(self, focusEvent):
        if not self._buttonHide.hasFocus():
            self._buttonUp.setVisible(False)
            self._buttonHide.setVisible(False)
            self._buttonDown.setVisible(False)
        QgsMapCanvas.focusOutEvent(self, focusEvent)

    def keyPressEvent(self, keyEvent):
        if keyEvent.key() == Qt.Key_Down:
            self.moveDown()
        elif keyEvent.key() == Qt.Key_Up:
            self.moveUp()
        elif keyEvent.key() == Qt.Key_H:
            self.toggleLayer()

    def keyPressed(self, keyEvent):
        pass

    def keyReleased(self, QKeyEvent):
        pass

    def keyReleaseEvent(self, QKeyEvent):
        pass

    def _getCanvas(self):
        return self._canvas

    canvas = property(_getCanvas)