Ejemplo n.º 1
0
class PM_ToolButtonGrid( PM_WidgetGrid ):
    """
    The PM_ToolButtonGrid widget provides a grid of tool buttons that function
    as an I{exclusive button group}.
    
    @see: B{PM_ElementChooser} for an example of how this is used.
    
    @todo: Fix button size issue (e.g. all buttons are sized 32 x 32).
    """
    
    buttonList       = []
    defaultCheckedId = -1    # -1 means no checked Id
    setAsDefault     = True
    
    
    def __init__(self, 
                 parentWidget, 
                 title        = '', 
                 buttonList   = [],
                 alignment    = None, 
                 label        = '',
                 labelColumn = 0,
                 spanWidth   = True,
                 checkedId    = -1, 
                 setAsDefault = False,   
                 isAutoRaise  = False,
                 isCheckable  = True
                 ):
        """
        Appends a PM_ToolButtonGrid widget to the bottom of I{parentWidget}, 
        the Property Manager Group box.
        
        @param parentWidget: The parent group box containing this widget.
        @type  parentWidget: PM_GroupBox
        
        @param title: The group box title.
        @type  title: str
        
        @param buttonList: A list of I{button info lists}. There is one button
                           info list for each button in the grid. The button
                           info list contains the following items:
                           1. Button Type - in this case its 'ToolButton'(str),
                           2. Button Id (int), 
                           3. Button text (str),
                           4. Button icon path (str),
                           5. Button tool tip (str),
                           6. Column (int), 
                           7. Row (int).
        @type  buttonList: list
        
        @param alignment:  The alignment of the toolbutton row in the parent 
                           groupbox. Based on its value,spacer items is added 
                           to the grid layout of the parent groupbox. 
        @type  alignment:  str
        
        @param label:      The label for the toolbutton row. If present, it is 
                           added to the same grid layout as the rest of the 
                           toolbuttons, in column number E{0}.
        @type  label:      str
        
        @param labelColumn: The column in the parentWidget's grid layout to which
                            this widget's label will be added. The labelColum
                            can only be E{0} or E{1}
        @type  labelColumn: int
        
        @param spanWidth: If True, the widget and its label will span the width
                      of the group box. Its label will appear directly above
                      the widget (unless the label is empty) and is left justified.
        @type  spanWidth: bool (default False)
                
        @param checkedId:  Checked button id in the button group. Default value
                           is -1 that implies no button is checked. 
        @type  checkedId:  int
        
        @param setAsDefault: If True, sets the I{checkedId} specified by the
                            user as the  default checked
        @type  setAsDefault: boolean
        """
                
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(True)
        
        self.isAutoRaise = isAutoRaise    
        self.isCheckable = isCheckable
        self.buttonsById   = {}
        self.buttonsByText = {}
        
        if setAsDefault:
            self.setDefaultCheckedId(checkedId)
        
                    
        PM_WidgetGrid.__init__(self, 
                               parentWidget , 
                               title, 
                               buttonList, 
                               alignment,
                               label,
                               labelColumn,
                               spanWidth
                              ) 
        
            
    def _createWidgetUsingParameters(self, widgetParams):
        """
        Returns a tool button created using the parameters specified by the user
        
        @param widgetParams: A list of label parameters. This is a modified
                             using the original list returned 
                             by L{self.getWidgetInfoList}. The modified list
                             doesn't contain the row and column information.
        @type  widgetParams: list
        @see:  L{PM_WidgetGrid._createWidgetUsingParameters} (overrided in this
               method)
        @see:  L{PM_WidgetGrid.loadWidgets} which calls this method. 
        
        """               
        buttonFont = self.getButtonFont() 
        buttonParams = list(widgetParams) 
        
        button = self._createToolButton(buttonParams)
        
        buttonId = buttonParams[1]     
        
        if self.defaultCheckedId == buttonId:
            button.setChecked(True)
        button.setFont(buttonFont)
        button.setAutoRaise(self.isAutoRaise)
        button.setCheckable(self.isCheckable)
        self.buttonGroup.addButton(button, buttonId)
        
        self.buttonsById[buttonId]    = button
        self.buttonsByText[str(button.text())] = button     
        
        return button
                   
        
    def getButtonFont(self):
        """
        Returns the font for the tool buttons in the grid.
        
        @return: Button font.
        @rtype:  U{B{QFont}<http://doc.trolltech.com/4/qfont.html>}
        """
        # Font for tool buttons.
        buttonFont = QFont(self.font())
        buttonFont.setFamily(BUTTON_FONT)
        buttonFont.setPointSize(BUTTON_FONT_POINT_SIZE)
        buttonFont.setBold(BUTTON_FONT_BOLD)
        return buttonFont              

    def restoreDefault(self):
        """
        Restores the default checkedId.
        """
        if self.setAsDefault:
            for buttonInfo in self.buttonList:
                buttonId = buttonInfo[0]
                if buttonId == self.defaultCheckedId:
                    button = self.getButtonById(buttonId)
                    button.setChecked(True)
        return
    
    def setDefaultCheckedId(self, checkedId):
        """
        Sets the default checked id (button) to I{checkedId}. The current checked
        button is unchanged.
                      
        @param checkedId: The new default id for the tool button group.
        @type  checkedId: int
        """
        self.setAsDefault = True
        self.defaultCheckedId = checkedId
        
    def checkedButton(self):
        """
        Returns the tool button group's checked button, or E{0} if no button is
        checked.
        @return: Checked tool button or E{0}
        @rtype:  instance of QToolButton  or int
        """
        return self.buttonGroup.checkedButton()
        
    def checkedId(self):
        """
        Returns the id of the checkedButton(), or -1 if no button is checked.
        
        @return: The checked button Id
        @rtype:  int
        """
        return self.buttonGroup.checkedId()
    
    def getButtonByText(self, text):
        """
        Returns the button with its current text set to I{text}.
        
        @return: The button, or B{None} if no button was found.
        @rtype:  U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>}
        
        @note: If multiple buttons have the same text, only the last one is returned.
        """
        if self.buttonsByText.has_key(text):
            return self.buttonsByText[text]
        else:
            return None
        
    def getButtonById(self, buttonId):
        """
        Returns the button with the button id of I{buttonId}.
        
        return: The button, or B{None} if no button was found.
        rtype:  U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>}
        """
        if self.buttonsById.has_key(buttonId):
            return self.buttonsById[buttonId]
        else:
            return None
    
    def setButtonSize(self, width = 32, height = 32):
        """
        """
        for btn in self.buttonGroup.buttons():
            btn.setFixedSize(QSize(width, height))
class PM_ToolButtonGrid(PM_WidgetGrid):
    """
    The PM_ToolButtonGrid widget provides a grid of tool buttons that function
    as an I{exclusive button group}.
    
    @see: B{PM_ElementChooser} for an example of how this is used.
    
    @todo: Fix button size issue (e.g. all buttons are sized 32 x 32).
    """

    buttonList = []
    defaultCheckedId = -1  # -1 means no checked Id
    setAsDefault = True

    def __init__(self,
                 parentWidget,
                 title='',
                 buttonList=[],
                 alignment=None,
                 label='',
                 labelColumn=0,
                 spanWidth=True,
                 checkedId=-1,
                 setAsDefault=False,
                 isAutoRaise=False,
                 isCheckable=True):
        """
        Appends a PM_ToolButtonGrid widget to the bottom of I{parentWidget}, 
        the Property Manager Group box.
        
        @param parentWidget: The parent group box containing this widget.
        @type  parentWidget: PM_GroupBox
        
        @param title: The group box title.
        @type  title: str
        
        @param buttonList: A list of I{button info lists}. There is one button
                           info list for each button in the grid. The button
                           info list contains the following items:
                           1. Button Type - in this case its 'ToolButton'(str),
                           2. Button Id (int), 
                           3. Button text (str),
                           4. Button icon path (str),
                           5. Button tool tip (str),
                           6. Column (int), 
                           7. Row (int).
        @type  buttonList: list
        
        @param alignment:  The alignment of the toolbutton row in the parent 
                           groupbox. Based on its value,spacer items is added 
                           to the grid layout of the parent groupbox. 
        @type  alignment:  str
        
        @param label:      The label for the toolbutton row. If present, it is 
                           added to the same grid layout as the rest of the 
                           toolbuttons, in column number E{0}.
        @type  label:      str
        
        @param labelColumn: The column in the parentWidget's grid layout to which
                            this widget's label will be added. The labelColum
                            can only be E{0} or E{1}
        @type  labelColumn: int
        
        @param spanWidth: If True, the widget and its label will span the width
                      of the group box. Its label will appear directly above
                      the widget (unless the label is empty) and is left justified.
        @type  spanWidth: bool (default False)
                
        @param checkedId:  Checked button id in the button group. Default value
                           is -1 that implies no button is checked. 
        @type  checkedId:  int
        
        @param setAsDefault: If True, sets the I{checkedId} specified by the
                            user as the  default checked
        @type  setAsDefault: boolean
        """

        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(True)

        self.isAutoRaise = isAutoRaise
        self.isCheckable = isCheckable
        self.buttonsById = {}
        self.buttonsByText = {}

        if setAsDefault:
            self.setDefaultCheckedId(checkedId)

        PM_WidgetGrid.__init__(self, parentWidget, title, buttonList,
                               alignment, label, labelColumn, spanWidth)

    def _createWidgetUsingParameters(self, widgetParams):
        """
        Returns a tool button created using the parameters specified by the user
        
        @param widgetParams: A list of label parameters. This is a modified
                             using the original list returned 
                             by L{self.getWidgetInfoList}. The modified list
                             doesn't contain the row and column information.
        @type  widgetParams: list
        @see:  L{PM_WidgetGrid._createWidgetUsingParameters} (overrided in this
               method)
        @see:  L{PM_WidgetGrid.loadWidgets} which calls this method. 
        
        """
        buttonFont = self.getButtonFont()
        buttonParams = list(widgetParams)

        button = self._createToolButton(buttonParams)

        buttonId = buttonParams[1]

        if self.defaultCheckedId == buttonId:
            button.setChecked(True)
        button.setFont(buttonFont)
        button.setAutoRaise(self.isAutoRaise)
        button.setCheckable(self.isCheckable)
        self.buttonGroup.addButton(button, buttonId)

        self.buttonsById[buttonId] = button
        self.buttonsByText[str(button.text())] = button

        return button

    def getButtonFont(self):
        """
        Returns the font for the tool buttons in the grid.
        
        @return: Button font.
        @rtype:  U{B{QFont}<http://doc.trolltech.com/4/qfont.html>}
        """
        # Font for tool buttons.
        buttonFont = QFont(self.font())
        buttonFont.setFamily(BUTTON_FONT)
        buttonFont.setPointSize(BUTTON_FONT_POINT_SIZE)
        buttonFont.setBold(BUTTON_FONT_BOLD)
        return buttonFont

    def restoreDefault(self):
        """
        Restores the default checkedId.
        """
        if self.setAsDefault:
            for buttonInfo in self.buttonList:
                buttonId = buttonInfo[0]
                if buttonId == self.defaultCheckedId:
                    button = self.getButtonById(buttonId)
                    button.setChecked(True)
        return

    def setDefaultCheckedId(self, checkedId):
        """
        Sets the default checked id (button) to I{checkedId}. The current checked
        button is unchanged.
                      
        @param checkedId: The new default id for the tool button group.
        @type  checkedId: int
        """
        self.setAsDefault = True
        self.defaultCheckedId = checkedId

    def checkedButton(self):
        """
        Returns the tool button group's checked button, or E{0} if no button is
        checked.
        @return: Checked tool button or E{0}
        @rtype:  instance of QToolButton  or int
        """
        return self.buttonGroup.checkedButton()

    def checkedId(self):
        """
        Returns the id of the checkedButton(), or -1 if no button is checked.
        
        @return: The checked button Id
        @rtype:  int
        """
        return self.buttonGroup.checkedId()

    def getButtonByText(self, text):
        """
        Returns the button with its current text set to I{text}.
        
        @return: The button, or B{None} if no button was found.
        @rtype:  U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>}
        
        @note: If multiple buttons have the same text, only the last one is returned.
        """
        if self.buttonsByText.has_key(text):
            return self.buttonsByText[text]
        else:
            return None

    def getButtonById(self, buttonId):
        """
        Returns the button with the button id of I{buttonId}.
        
        return: The button, or B{None} if no button was found.
        rtype:  U{B{QToolButton}<http://doc.trolltech.com/4/qtoolbutton.html>}
        """
        if self.buttonsById.has_key(buttonId):
            return self.buttonsById[buttonId]
        else:
            return None

    def setButtonSize(self, width=32, height=32):
        """
        """
        for btn in self.buttonGroup.buttons():
            btn.setFixedSize(QSize(width, height))
Ejemplo n.º 3
0
class Ui_CommandToolbar( QWidget ):
    """ 
    This provides most of the User Interface for the command toolbar 
    called in CommandToolbar class.
    """
    def __init__(self, win):
        """
        Constructor for class Ui_CommandToolbar.
        
        @param win: Mainwindow object
        @type  win: L{MWsemantics}
        """
        QWidget.__init__(self)
        
        self.win = win
    
    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
    
    def truncateText(self, text, length = 12, truncateSymbol = '...'):
        """
        Truncates the tooltip text with the given truncation symbol
        (three dots) in the case 
        """
            
        #ninad 070201 This is a temporary fix. Ideally it should show the whole
        #text in the  toolbutton. But there are some layout / size policy 
        #problems because of which the toolbar height increases after you print
        #tooltip text on two or more lines. (undesirable effect) 
            
        if not text:
            print "no text to truncate. Returning"
            return 
        
        truncatedLength  = length - len(truncateSymbol)
        
        if len(text) > length:
            return text[:truncatedLength] + truncateSymbol
        else:
            return text
        
                
                        
    def wrapToolButtonText(self, text):
        """
        Add a newline character at the end of each word in the toolbutton text
        """
        #ninad 070126 QToolButton lacks this method. This is not really a 
        #'word wrap' but OK for now. 
        
        #@@@ ninad 070126. Not calling this method as it is creating an annoying
        #resizing problem in the Command toolbar layout. Possible solution is 
        #to add a spacer item in a vbox layout to the command toolbar layout
        
        stringlist = text.split(" ", QString.SkipEmptyParts)
        text2 = QString()
        if len(stringlist) > 1:
            for l in stringlist:
                text2.append(l)
                text2.append("\n")
            return text2
                
        return None
    
    ##==================================================================##
    #color palettes (UI stuff) for different command toolbar areas
   
    def getCmdMgrCtrlAreaPalette(self): 
        """ Return a palette for Command Manager control area 
        (Palette for Tool Buttons in command toolbar control area)
        """
        #See comment at the top for details about this flag
        if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
            return getPalette(None,
                              QPalette.Window,
                              cmdTbarCntrlAreaBtnColor
                              )
        else:
            return getPalette(None,
                              QPalette.Button,
                              cmdTbarCntrlAreaBtnColor
                              )
            
    
    def getCmdMgrSubCtrlAreaPalette(self):
        """ Return a palette for Command Manager sub control area 
        (Palette for Tool Buttons in command toolbar sub control area)
        """
        #Define the color role. Make sure to apply color to QPalette.Button 
        #instead of QPalette.Window as it is a QToolBar. - ninad 20070619
        
        return getPalette(None,
                          QPalette.Button,
                          cmdTbarSubCntrlAreaBtnColor
                          )
    
    def getCmdMgrCommandAreaPalette(self):
        """ Return a palette for Command Manager 'Commands area'(flyout toolbar)
        (Palette for Tool Buttons in command toolbar command area)
        """
        return self.flyoutToolBar.getPalette()