当前位置: 首页>>代码示例>>Python>>正文


Python QButtonGroup.buttons方法代码示例

本文整理汇总了Python中PyQt4.QtGui.QButtonGroup.buttons方法的典型用法代码示例。如果您正苦于以下问题:Python QButtonGroup.buttons方法的具体用法?Python QButtonGroup.buttons怎么用?Python QButtonGroup.buttons使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtGui.QButtonGroup的用法示例。


在下文中一共展示了QButtonGroup.buttons方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ActionsPane

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class ActionsPane(QWidget):
    def __init__(self):
        super().__init__()

        self.group = QButtonGroup()
        self.group.setExclusive(False)

        self.scope_widget = ActionsScope()
        self.action_buttons = QVBoxLayout()
        self.big_red_button = QPushButton("Automate !!!", clicked=self.automate)
        self.big_red_button.setStyleSheet("QPushButton { background-color : red}")

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.layout.addWidget(self.scope_widget)
        self.layout.addLayout(self.action_buttons)
        self.layout.addStretch()
        self.layout.addWidget(self.big_red_button)

    def registerAction(self, action):
        button = ActionButton(action)
        self.group.addButton(button.checkbox)
        self.action_buttons.addWidget(button)

    def getCheckedActions(self):
        return [btn.parent().action for btn in self.group.buttons() if btn.isChecked()]

    def automate(self, event):
        for action in self.getCheckedActions():
            action.on_triggered()
开发者ID:Atlantic777,项目名称:perf_test_runner,代码行数:33,代码来源:widgets.py

示例2: ScopeBox

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class ScopeBox(QGroupBox):
    title = None
    button_type = None

    def __init__(self):
        if self.title is None or self.button_type is None:
            raise Exception("Still too abstract!")

        super().__init__(title=self.title)

        self.populate_button_id()
        self.build_layout()
        self.populate_box()
        self.select_default()

        if self.button_type == 'check':
            self.group.setExclusive(False)

    def populate_button_id(self):
        pass

    def build_layout(self):
        self.group = QButtonGroup()
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

    def populate_box(self):
        keys = list(self.button_id.keys())
        keys.sort()

        BtnClass = None
        if self.button_type == 'check':
            BtnClass = QCheckBox
        elif self.button_type == 'radio':
            BtnClass = QRadioButton

        for key in keys:
            btn = BtnClass(key)
            self.layout.addWidget(btn)
            self.group.addButton(btn, self.button_id[key])

    def select_default(self):
        pass

    def getSelection(self):
        selection = None

        if self.button_type == 'radio':
            selection = self.group.checkedId()
        elif self.button_type == 'check':
            selection = []

            for btn in self.group.buttons():
                if btn.isChecked():
                    selection.append(btn.text())

        return selection
开发者ID:Atlantic777,项目名称:perf_test_runner,代码行数:59,代码来源:widgets.py

示例3: DefaultSelectParameterWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]

#.........这里部分代码省略.........

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index, Qt.UserRole) != (
                self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
开发者ID:timlinux,项目名称:inasafe,代码行数:104,代码来源:default_select_parameter_widget.py

示例4: OptionWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class OptionWidget(EditorWidget):
    widgettype = 'Option Row'

    def __init__(self, *args, **kwargs):
        super(OptionWidget, self).__init__(*args, **kwargs)
        self._bindvalue = None
        self.group = QButtonGroup()
        self.group.buttonClicked.connect(self.emitvaluechanged)

    def createWidget(self, parent=None):
        widget = QWidget(parent)
        return widget

    def _buildfromlist(self, listconfig, multiselect):
        def chunks(l, n):
            """ Yield successive n-sized chunks from l.
            """
            for i in xrange(0, len(l), n):
                yield l[i:i+n]

        items = listconfig['items']
        wrap = self.config.get('wrap', 0)
        showcolor = self.config.get('always_color', False)
        if wrap > 0:
            rows = list(chunks(items, wrap))
        else:
            rows = [items]

        for rowcount, row in enumerate(rows):
            for column, item in enumerate(row):
                parts = item.split(';')
                data = parts[0]
                try:
                    desc = parts[1]
                except IndexError:
                    desc = data

                button = QPushButton()
                button.setCheckable(multiselect)
                self.group.setExclusive(not multiselect)

                icon = QIcon()
                try:
                    path = parts[2]
                    if path.startswith("#"):
                        # Colour the button with the hex value.
                        # If show color is enabled we always show the color regardless of selection.
                        print showcolor
                        if not showcolor:
                            style = """
                                QPushButton::checked {{
                                    border: 3px solid rgb(137, 175, 255);
                                    background-color: {colour};
                                }}""".format(colour=path)
                        else:
                            style = """
                                QPushButton::checked {{
                                    border: 3px solid rgb(137, 175, 255);
                                }}
                                QPushButton {{
                                    background-color: {colour};
                                }}""".format(colour=path)
                        button.setStyleSheet(style)
                    elif path.endswith("_icon"):
                        icon = QIcon(":/icons/{}".format(path))
                    else:
                        icon = QIcon(path)
                except:
                    icon = QIcon()

                button.setCheckable(True)
                button.setText(desc)
                button.setProperty("value", data)
                button.setIcon(icon)
                button.setIconSize(QSize(24, 24))
                if isinstance(self.widget.layout(), QBoxLayout):
                    self.widget.layout().addWidget(button)
                else:
                    self.widget.layout().addWidget(button, rowcount, column)
                self.group.addButton(button)

    def initWidget(self, widget, config):
        if not widget.layout():
            widget.setLayout(QGridLayout())
            widget.layout().setContentsMargins(0, 0, 0, 0)

    def updatefromconfig(self):
        super(OptionWidget, self).updatefromconfig()

        for button in self.group.buttons():
            self.group.removeButton(button)
            self.widget.layout().removeWidget(button)
            button.deleteLater()
            button.setParent(None)

        listconfig = self.config['list']
        multiselect = self.config.get('multi', False)
        self._buildfromlist(listconfig, multiselect)

        super(OptionWidget, self).endupdatefromconfig()
#.........这里部分代码省略.........
开发者ID:skeenp,项目名称:Roam,代码行数:103,代码来源:optionwidget.py

示例5: OptionWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class OptionWidget(EditorWidget):
    widgettype = 'Option Row'

    def __init__(self, *args):
        super(OptionWidget, self).__init__(*args)
        self._bindvalue = None
        self.group = QButtonGroup()
        self.group.setExclusive(True)
        self.group.buttonClicked.connect(self.emitvaluechanged)

    def createWidget(self, parent):
        widget = QWidget(parent)
        return widget

    def _buildfromlist(self, listconfig):
        items = listconfig['items']
        for item in items:
            parts = item.split(';')
            data = parts[0]
            try:
                desc = parts[1]
            except IndexError:
                desc = data

            button = QPushButton()

            icon = QIcon()
            try:
                path = parts[2]
                if path.startswith("#"):
                    # Colour the button with the hex value
                    style = """
                        QPushButton:checked  {{
                            border: 3px solid rgb(137, 175, 255);
                        background-color: {colour};
                        }}""".format(colour=path)
                    button.setStyleSheet(style)
                elif path.endswith("_icon"):
                    icon = QIcon(":/icons/{}".format(path))
                else:
                    icon = QIcon(path)
            except:
                icon = QIcon()

            button.setCheckable(True)
            button.setText(desc)
            button.setProperty("value", data)
            button.setIcon(icon)
            button.setIconSize(QSize(24, 24))
            self.widget.layout().addWidget(button)
            self.group.addButton(button)

    def initWidget(self, widget):
        if not widget.layout():
            widget.setLayout(QHBoxLayout())
            widget.layout().setContentsMargins(0, 0, 0, 0)

    def updatefromconfig(self):
        super(OptionWidget, self).updatefromconfig()

        for button in self.group.buttons():
            self.group.removeButton(button)
            self.widget.layout().removeWidget(button)
            button.deleteLater()
            button.setParent(None)

        listconfig = self.config['list']
        self._buildfromlist(listconfig)

        super(OptionWidget, self).endupdatefromconfig()

    def validate(self, *args):
        button = self.group.checkedButton()
        if button:
            return True

        return False

    @property
    def nullvalues(self):
        return ['NULL']

    def setvalue(self, value):
        if value in self.nullvalues:
            value = None

        for button in self.group.buttons():
            buttonvalue = button.property("value")
            if (value is None and buttonvalue in self.nullvalues) or buttonvalue == str(value):
                button.setChecked(True)
                self.emitvaluechanged()
                return

    def value(self):
        button = self.group.checkedButton()
        if not button:
            return None

        value = button.property("value")

#.........这里部分代码省略.........
开发者ID:HeatherHillers,项目名称:Roam,代码行数:103,代码来源:optionwidget.py

示例6: XNavigationEdit

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]

#.........这里部分代码省略.........
                return True
                
            elif ( event.key() == Qt.Key_Tab ):
                if ( self.completer().popup().isVisible() ):
                    text   = str(self.completer().currentCompletion())
                    super(XNavigationEdit, self).setText(text)
                    return True
                else:
                    self.acceptEdit()
                    return False
            
        elif ( event.type() == event.MouseButtonPress ):
            if ( not self._completerTree.rect().contains(event.pos()) ):
                self._completerTree.hide()
                self.completer().popup().hide()
                
                self.cancelEdit()
        
        return False
    
    def focusOutEvent( self, event ):
        """
        Overloads the focus out event to cancel editing when the widget loses
        focus.
        
        :param      event | <QFocusEvent>
        """
        super(XNavigationEdit, self).focusOutEvent(event)
        
        self.cancelEdit()
    
    def handleButtonClick( self, button ):
        """
        Handle the event when a user clicks on one of the part buttons.
        
        :param      button | <QToolButton>
        """
        path            = button.property('path')
        is_completer    = button.property('is_completer')
        
        # popup a completion menu
        if ( unwrapVariant(is_completer) ):
            model = self.navigationModel()
            if ( not model ):
                return
            
            sep  = self.separator()
            path = str(unwrapVariant(path))
            item = model.itemByPath(path, includeRoot = True)
            if ( not item ):
                return
            
            curr_path = str(self.text()).strip(self.separator())
            curr_path = curr_path.replace(path, '').strip(self.separator())
            
            child_name = ''
            if ( curr_path ):
                child_name = curr_path.split(self.separator())[0]
            
            index = model.indexFromItem(item)
            
            self._completerTree.move(QCursor.pos())
            self._completerTree.setRootIndex(index)
            self._completerTree.verticalScrollBar().setValue(0)
            
            if ( child_name ):
开发者ID:satishgoda,项目名称:DPS_PIPELINE,代码行数:70,代码来源:xnavigationedit.py

示例7: FilteringModule

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]

#.........这里部分代码省略.........
        # Opens the file browser, starting at the home directory.
        start_file = os.path.expanduser('~/')
        # Get the file path from the browser window.
        path = QFileDialog.getOpenFileName(self, 'Open a stop words source',
                                           start_file, self.dlgFormats)
        if not path:
            return

        if path in self.recent_sw_files:
            self.recent_sw_files.remove(path)
        self.recent_sw_files.insert(0, path)
        self.set_file_list()
        self.open_file(path)

    def update_df_parameters(self):
        min_df = None if not self.min_df_input.text() else self.min_df_input.text()
        max_df = None if not self.max_df_input.text() else self.max_df_input.text()
        self.filtering_values[self.DocumentFrequency] = (min_df, max_df)
        self.notify_on_change()

    def open_file(self, path):
        try:
            with open(path) as f:  # Read most recent.
                self.filtering_values[self.Custom] = [sw.strip() for sw in
                                                      f.read().splitlines()]
                self.notify_on_change()
        except Exception:  # Raise an exception otherwise.
            self.send_message('Could not open "{}".'
                              .format(path))

    def on_reload_button_clicked(self):
        if self.recent_sw_files:
            self.select_file(0)
    # END File selection.

    def group_button_clicked(self):
        self.filtering_methods = [ch_box.isChecked() for ch_box in
                                  self.group.buttons()]

        self.enable_choice_settings()

        # Emit the signal.
        self.notify_on_change()

    def enable_choice_settings(self):
        self.sw_file_combo.setEnabled(self.filtering_methods[1])
        self.browse_button.setEnabled(self.filtering_methods[1])
        self.reload_button.setEnabled(self.filtering_methods[1])

        self.min_df_input.setEnabled(self.filtering_methods[2])
        self.max_df_input.setEnabled(self.filtering_methods[2])

    def get_pp_setting(self):
        flag_english = self.filtering_methods[0]
        flag_custom = self.filtering_methods[1]
        flag_df = self.filtering_methods[2]
        if flag_english and flag_custom:  # Use custom.
            stop_words = {
                'stop_words': stopwords.words('english') +
                              self.filtering_values[self.Custom]
            }
        elif flag_english and not flag_custom:
            stop_words = {
                'stop_words': 'english'
            }
        elif flag_custom:
            stop_words = {
                'stop_words': self.filtering_values[self.Custom]
            }
        else:
            stop_words = {}

        if flag_df:
            stop_words.update({
                'min_df': self.str_to_num(self.min_df_input.text()),
                'max_df': self.str_to_num(self.max_df_input.text()),
            })
        return stop_words

    def restore_data(self, data):
        self.recent_sw_files = data.get('recent_sw_files')
        self.min_df_input.setText(data.get('min_df'))
        self.max_df_input.setText(data.get('max_df'))
        self.filtering_methods = data.get('methods')

        for flag, ch_box in zip(self.filtering_methods, self.group.buttons()):
            ch_box.setChecked(flag)

        self.enable_choice_settings()  # Enable the settings if set.
        self.set_file_list()  # Fill the combo box with the recent sw files.
        self.select_file(0)  # Select the first file.

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'methods': self.filtering_methods,
            'recent_sw_files': self.recent_sw_files,
            'min_df': self.min_df_input.text(),
            'max_df': self.max_df_input.text(),
        }
开发者ID:david-novak,项目名称:orange3-text,代码行数:104,代码来源:owpreprocess.py

示例8: OptionWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class OptionWidget(EditorWidget):
    widgettype = 'Option Row'
    def __init__(self, *args):
        super(OptionWidget, self).__init__(*args)
        self._bindvalue = None
        self.group = QButtonGroup()
        self.group.setExclusive(True)
        self.group.buttonClicked.connect(self.emitvaluechanged)

    def createWidget(self, parent):
        widget = QWidget(parent)
        widget.setLayout(QHBoxLayout())
        widget.layout().setContentsMargins(0,0,0,0)
        return widget

    def _buildfromlist(self, listconfig):
        items = listconfig['items']
        for item in items:
            parts = item.split(';')
            data = parts[0]
            try:
                desc = parts[1]
            except IndexError:
                desc = data

            try:
                path = parts[2]
                if path.endswith("_icon"):
                    icon = QIcon(":/icons/{}".format(path))
                else:
                    icon = QIcon(path)
            except:
                icon = QIcon()


            button = QPushButton()
            button.setCheckable(True)
            button.setText(desc)
            button.setProperty("value", data)
            button.setIcon(icon)
            button.setIconSize(QSize(24,24))
            self.widget.layout().addWidget(button)
            self.group.addButton(button)

    def initWidget(self, widget):
        pass

    def updatefromconfig(self):
        super(OptionWidget, self).updatefromconfig()
        listconfig = self.config['list']
        self._buildfromlist(listconfig)

        super(OptionWidget, self).endupdatefromconfig()

    def validate(self, *args):
        button = self.group.checkedButton()
        if button:
            self.raisevalidationupdate(True)
        else:
            self.raisevalidationupdate(False)
        self.emitvaluechanged()

    def setvalue(self, value):
        for button in self.group.buttons():
            if button.property("value") == value:
                button.setChecked(True)
                return

    def value(self):
        button = self.group.checkedButton()
        if not button:
            return None
        return button.property("value")
开发者ID:henriquespedro,项目名称:Roam,代码行数:75,代码来源:optionwidget.py

示例9: DBDatabasesWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class DBDatabasesWidget(QWidget):
    """Displays a list of Databases"""

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.debug = False
        
        self.db = None
        
        self.setWindowTitle("Databases")
        #s#elf.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)

        
        self.mainLayout = QVBoxLayout()
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(0)
        self.setLayout(self.mainLayout)

        #=============================================
        ## Top Toolbar
        topBar = QToolBar()
        topBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainLayout.addWidget(topBar)
        
        ## Add the action buttons
        topBar.addAction(Ico.icon(Ico.ServerAdd), "Add", self.on_server_add)
        self.actionServerEdit = topBar.addAction(Ico.icon(Ico.ServerEdit), "Edit", self.on_server_edit)
        self.actionServerDelete = topBar.addAction(Ico.icon(Ico.ServerDelete), "Delete", self.on_server_delete)
        
        #=============================================
        ## Tree
        self.tree = QTreeWidget()
        self.mainLayout.addWidget(self.tree)
        self.tree.setHeaderLabels(["Server", "User", ""])
        self.tree.setUniformRowHeights(True)
        self.tree.setRootIsDecorated(False)
        self.tree.setColumnWidth(C.widget, 20)
        
        
        self.connect( self.tree, SIGNAL( 'itemSelectionChanged()' ), self.on_tree_selection_changed )
        self.connect( self.tree, SIGNAL( 'itemDoubleClicked (QTreeWidgetItem *,int)' ), self.on_tree_double_clicked )
    
        self.buttGroup = QButtonGroup(self)
        self.connect(self.buttGroup, SIGNAL("buttonClicked(QAbstractButton*)"), self.on_open_server)
    
        self.on_tree_selection_changed()
    
    
        self.load_servers()
        
    #=======================================
    ##== Tree Events
    def on_tree_selection_changed(self):
        
        disabled = self.tree.selectionModel().hasSelection() == False
        self.actionServerEdit.setDisabled(disabled)
        self.actionServerDelete.setDisabled(disabled)
        
    def on_tree_double_clicked(self):
        self.actionServerEdit.trigger()


    
    #=======================================
    ## Server Actions
    def on_server_add(self):
        self.show_server_dialog(None)
        
    def on_server_edit(self):
        item = self.tree.currentItem()
        if item == None:
            return
        server = str(item.text(C.server))
        self.show_server_dialog(server)
    
    def show_server_dialog(self, server=None):
        d = DBServerDialog.DBServerDialog(self, server)
        if d.exec_():
            self.load_servers()
       
       
    def on_open_server(self, butt):
        self.emit(SIGNAL("open_server"), butt.property("server").toString())
              
             
    
    def load_servers(self):
        """Load servers from :py:meth:`pyqtdb.XSettings.XSettings.get_servers` """
        
        self.tree.clear()
        
        for butt in self.buttGroup.buttons():
            self.buttGroup.removeButton(butt)
        
        for srv in G.settings.get_servers_list():
            
            item = QTreeWidgetItem()
            item.setText(C.server, srv['server'])
            item.setText(C.user, srv['user'])
#.........这里部分代码省略.........
开发者ID:pedromorgan,项目名称:PyQtDb,代码行数:103,代码来源:DBDatabasesWidget.py

示例10: DBServersWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class DBServersWidget(QWidget):
    """Displays a list of servers"""

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.debug = False
        
        self.connections = {}
        
        self.setWindowTitle("Servers")
        #s#elf.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)

        
        self.mainLayout = QVBoxLayout()
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(0)
        self.setLayout(self.mainLayout)

        #=============================================
        ## Top Toolbar
        topBar = QToolBar()
        topBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainLayout.addWidget(topBar)
        
        ## Add the action buttons
        topBar.addAction(Ico.icon(Ico.ServerAdd), "Add", self.on_server_add)
        self.actionServerEdit = topBar.addAction(Ico.icon(Ico.ServerEdit), "Edit", self.on_server_edit)
        self.actionServerDelete = topBar.addAction(Ico.icon(Ico.ServerDelete), "Delete", self.on_server_delete)
        
        #=============================================
        ## Tree
        self.tree = QTreeWidget()
        self.mainLayout.addWidget(self.tree)
        self.tree.setUniformRowHeights(True)
        self.tree.setRootIsDecorated(True)
        
        
        self.tree.setHeaderLabels(["Server", "Butt"]) # set header, but hide anyway
        self.tree.header().hide()
        self.tree.header().setResizeMode(C.node, QHeaderView.Stretch)
        self.tree.setColumnWidth(C.butt, 20)
        
        
        self.connect( self.tree, SIGNAL( 'itemSelectionChanged()' ), self.on_tree_selection_changed )
        self.connect( self.tree, SIGNAL( 'itemDoubleClicked (QTreeWidgetItem *,int)' ), self.on_tree_double_clicked )
    
        self.buttGroup = QButtonGroup(self)
        self.connect(self.buttGroup, SIGNAL("buttonClicked(QAbstractButton*)"), self.on_open_server)
    
        self.on_tree_selection_changed()
    
    
        self.load_servers()
        
    #=======================================
    ##== Tree Events
    def on_tree_selection_changed(self):
        
        disabled = self.tree.selectionModel().hasSelection() == False
        self.actionServerEdit.setDisabled(disabled)
        self.actionServerDelete.setDisabled(disabled)
        
    def on_tree_double_clicked(self):
        self.actionServerEdit.trigger()


    
    #=======================================
    ## Server Actions
    def on_server_add(self):
        self.show_server_dialog(None)
        
    def on_server_edit(self):
        item = self.tree.currentItem()
        if item == None:
            return
        server = str(item.text(C.server))
        self.show_server_dialog(server)
    
    def show_server_dialog(self, server=None):
        d = DBServerDialog.DBServerDialog(self, server)
        if d.exec_():
            self.load_servers()
    

            
    
    def load_servers(self):
        """Load servers from :py:meth:`pyqtdb.XSettings.XSettings.get_servers` """
        
        self.tree.clear()
        
        for butt in self.buttGroup.buttons():
            self.buttGroup.removeButton(butt)
        
        for srv in G.settings.get_servers_list():
            
            item = QTreeWidgetItem()
            item.setText(C.node, srv['server'])
#.........这里部分代码省略.........
开发者ID:pedromorgan,项目名称:PyQtDb,代码行数:103,代码来源:DBServersWidget.py

示例11: PeriodicTableWidget

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]
class PeriodicTableWidget(QWidget):
    selectionChanged = pyqtSignal()
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        # Widgets, layouts and signals
        self._group = QButtonGroup()
        layout = QGridLayout()
        layout.setSpacing(0)
        ## Element
        for z, position in _ELEMENT_POSITIONS.items():
            widget = ElementPushButton(z)
            widget.setStyle(QStyleFactory.create("windows"))
            widget.setCheckable(True)
            layout.addWidget(widget, *position)
            self._group.addButton(widget, z)
        ## Labels
        layout.addWidget(QLabel(''), 7, 0) # Dummy
        layout.addWidget(QLabel('*'), 5, 2, Qt.AlignRight)
        layout.addWidget(QLabel('*'), 8, 2, Qt.AlignRight)
        layout.addWidget(QLabel('**'), 6, 2, Qt.AlignRight)
        layout.addWidget(QLabel('**'), 9, 2, Qt.AlignRight)

        for row in [0, 1, 2, 3, 4, 5, 6, 8, 9]:
            layout.setRowStretch(row, 1)

        self.setLayout(layout)

        # Signals
        self._group.buttonClicked.connect(self.selectionChanged)

        # Default
        self.setColorFunction(_category_color_function)

    def setColorFunction(self, func):
        if not callable(func):
            raise ValueError('Not a function')
        self._color_function = func

        # Redraw
        for widget in self._group.buttons():
            z = self._group.id(widget)
            bcolor = func(z)
            fcolor = 'white' if _calculate_brightness(bcolor) < 128 else 'black'
            sheet = 'background-color: %s; color: %s' % (bcolor.name(), fcolor)
            widget.setStyleSheet(sheet)

    def colorFunction(self):
        return self._color_function

    def setSelection(self, selection):
        self.selectionChanged.emit()
#
    def selection(self):
        selection = None
        for widget in self._group.buttons():
            if widget.isChecked():
                selection = self._group.id(widget)
        if selection != None:
            return [selection, get_symbol(selection)]
        else:
            return None
开发者ID:shrx,项目名称:moldy,代码行数:63,代码来源:widgets.py

示例12: PrivacyConfirmationDialog

# 需要导入模块: from PyQt4.QtGui import QButtonGroup [as 别名]
# 或者: from PyQt4.QtGui.QButtonGroup import buttons [as 别名]

#.........这里部分代码省略.........
        scopeWidget = QWidget(self)
        self._scopeGroup = QButtonGroup(self)

        if not self._useCategories:
            thisPeer = QRadioButton(peerName, scopeWidget)
            thisPeer.clicked.connect(partial(self._setScope, self.SCOPE_PEER))
            self._scopeGroup.addButton(thisPeer)

            everyone = QRadioButton(u"Everyone", scopeWidget)
            everyone.clicked.connect(partial(self._setScope, self.SCOPE_EVERYONE))
            self._scopeGroup.addButton(everyone)
        else:
            if self._category == PrivacySettings.NO_CATEGORY:
                catDesc = u"uncategorized"
            else:
                catDesc = u"category %s" % category

            b = QRadioButton(u"%s, %s" % (peerName, catDesc), scopeWidget)
            b.clicked.connect(partial(self._setScope, self.SCOPE_PEER_CATEGORY))
            self._scopeGroup.addButton(b)

            b = QRadioButton(u"%s, all categories" % (peerName), scopeWidget)
            b.clicked.connect(partial(self._setScope, self.SCOPE_PEER))
            self._scopeGroup.addButton(b)

            b = QRadioButton(u"Everyone, %s" % (catDesc), scopeWidget)
            b.clicked.connect(partial(self._setScope, self.SCOPE_EVERYONE_CATEGORY))
            self._scopeGroup.addButton(b)

            b = QRadioButton(u"Everyone, all categories", scopeWidget)
            b.clicked.connect(partial(self._setScope, self.SCOPE_EVERYONE))
            self._scopeGroup.addButton(b)

        self._scopeGroup.buttons()[0].click()
        scopeLayout = QVBoxLayout(scopeWidget)
        scopeLayout.setContentsMargins(5, 0, 5, 0)
        for button in self._scopeGroup.buttons():
            scopeLayout.addWidget(button, 0)
        return scopeWidget

    def _initButtonBox(self):
        cancelButton = QPushButton("Deny", self)
        cancelButton.clicked.connect(self.reject)

        okButton = QPushButton("Accept", self)
        okButton.clicked.connect(self.accept)

        buttonBox = QDialogButtonBox(Qt.Horizontal, self)
        buttonBox.addButton(cancelButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(okButton, QDialogButtonBox.AcceptRole)
        return buttonBox

    def _setPolicy(self, policy):
        self._policy = policy
        for button in self._scopeGroup.buttons():
            button.setEnabled(policy == self.POLICY_FOREVER)

    def _setScope(self, scope):
        self._scope = scope

    def _clickNext(self, group):
        curIdx = group.buttons().index(group.checkedButton())
        if curIdx + 1 < len(group.buttons()):
            group.buttons()[curIdx + 1].click()

    def _clickPrev(self, group):
开发者ID:hannesrauhe,项目名称:lunchinator,代码行数:70,代码来源:confirmation_dialog.py


注:本文中的PyQt4.QtGui.QButtonGroup.buttons方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。