本文整理汇总了Python中qtpy.QtWidgets.QComboBox.addItem方法的典型用法代码示例。如果您正苦于以下问题:Python QComboBox.addItem方法的具体用法?Python QComboBox.addItem怎么用?Python QComboBox.addItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qtpy.QtWidgets.QComboBox
的用法示例。
在下文中一共展示了QComboBox.addItem方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_controls
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
def create_controls(self):
self.setWindowTitle(tr(self.plugin.name))
vbox = QVBoxLayout()
form = QFormLayout()
for Name, (enabled, url) in self.packages.items():
name = Name.lower()
cbo = QComboBox()
if enabled:
branches = get_branches(name, url)
for n, b in branches.items():
cbo.addItem(n, b)
if not check_git_repo(name):
cbo.insertItem(0, "<Select to change>", None)
cbo.setCurrentIndex(0)
self._prev_indices[cbo] = 0
cbo.currentIndexChanged.connect(
partial(self._cbo_changed, cbo))
else:
cbo.setEditText("<git repository>")
cbo.setToolTip(tr(
"This is installed in a git repository but we're set to "
"not use git."))
cbo.setEnabled(enabled)
form.addRow(Name + ':', cbo)
vbox.addLayout(form)
vbox.addWidget(QLabel(tr(
"You should restart the application if you make any changes!")))
btns = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self)
btns.accepted.connect(self.accept)
vbox.addWidget(btns)
self.setLayout(vbox)
示例2: FormComboWidget
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class FormComboWidget(QWidget):
update_buttons = Signal()
def __init__(self, datalist, comment="", parent=None):
QWidget.__init__(self, parent)
layout = QVBoxLayout()
self.setLayout(layout)
self.combobox = QComboBox()
layout.addWidget(self.combobox)
self.stackwidget = QStackedWidget(self)
layout.addWidget(self.stackwidget)
self.combobox.currentIndexChanged.connect(
self.stackwidget.setCurrentIndex)
self.widgetlist = []
for data, title, comment in datalist:
self.combobox.addItem(title)
widget = FormWidget(data, comment=comment, parent=self)
self.stackwidget.addWidget(widget)
self.widgetlist.append(widget)
def setup(self):
for widget in self.widgetlist:
widget.setup()
def get(self):
return [ widget.get() for widget in self.widgetlist]
示例3: create_combobox
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
def create_combobox(self, text, choices, option, default=NoDefault,
tip=None, restart=False):
"""choices: couples (name, key)"""
label = QLabel(text)
combobox = QComboBox()
if tip is not None:
combobox.setToolTip(tip)
for name, key in choices:
if not (name is None and key is None):
combobox.addItem(name, to_qvariant(key))
# Insert separators
count = 0
for index, item in enumerate(choices):
name, key = item
if name is None and key is None:
combobox.insertSeparator(index + count)
count += 1
self.comboboxes[combobox] = (option, default)
layout = QHBoxLayout()
layout.addWidget(label)
layout.addWidget(combobox)
layout.addStretch(1)
layout.setContentsMargins(0, 0, 0, 0)
widget = QWidget(self)
widget.label = label
widget.combobox = combobox
widget.setLayout(layout)
combobox.restart_required = restart
combobox.label_text = text
return widget
示例4: RunConfigDialog
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class RunConfigDialog(BaseRunConfigDialog):
"""Run configuration dialog box: multiple file version"""
def __init__(self, parent=None):
BaseRunConfigDialog.__init__(self, parent)
self.file_to_run = None
self.combo = None
self.stack = None
def run_btn_clicked(self):
"""Run button was just clicked"""
self.file_to_run = to_text_string(self.combo.currentText())
def setup(self, fname):
"""Setup Run Configuration dialog with filename *fname*"""
combo_label = QLabel(_("Select a run configuration:"))
self.combo = QComboBox()
self.combo.setMaxVisibleItems(20)
self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.stack = QStackedWidget()
configurations = _get_run_configurations()
for index, (filename, options) in enumerate(configurations):
if fname == filename:
break
else:
# There is no run configuration for script *fname*:
# creating a temporary configuration that will be kept only if
# dialog changes are accepted by the user
configurations.insert(0, (fname, RunConfiguration(fname).get()))
index = 0
for filename, options in configurations:
widget = RunConfigOptions(self)
widget.set(options)
self.combo.addItem(filename)
self.stack.addWidget(widget)
self.combo.currentIndexChanged.connect(self.stack.setCurrentIndex)
self.combo.setCurrentIndex(index)
self.add_widgets(combo_label, self.combo, 10, self.stack)
self.add_button_box(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.setWindowTitle(_("Run configuration per file"))
def accept(self):
"""Reimplement Qt method"""
configurations = []
for index in range(self.stack.count()):
filename = to_text_string(self.combo.itemText(index))
runconfigoptions = self.stack.widget(index)
if index == self.stack.currentIndex() and\
not runconfigoptions.is_valid():
return
options = runconfigoptions.get()
configurations.append( (filename, options) )
_set_run_configurations(configurations)
QDialog.accept(self)
示例5: ConfigDialog
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class ConfigDialog(QDialog):
"""
Dialog window for specifying test configuration.
The window contains a combobox with all the frameworks, a line edit box for
specifying the working directory, a button to use a file browser for
selecting the directory, and OK and Cancel buttons. Initially, no framework
is selected and the OK button is disabled. Selecting a framework enables
the OK button.
"""
def __init__(self, frameworks, config, parent=None):
"""
Construct a dialog window.
Parameters
----------
frameworks : dict of (str, type)
Names of all supported frameworks with their associated class
(assumed to be a subclass of RunnerBase)
config : Config
Initial configuration
parent : QWidget
"""
super(ConfigDialog, self).__init__(parent)
self.setWindowTitle(_('Configure tests'))
layout = QVBoxLayout(self)
framework_layout = QHBoxLayout()
framework_label = QLabel(_('Test framework'))
framework_layout.addWidget(framework_label)
self.framework_combobox = QComboBox(self)
for ix, (name, runner) in enumerate(sorted(frameworks.items())):
installed = runner.is_installed()
if installed:
label = name
else:
label = '{} ({})'.format(name, _('not available'))
self.framework_combobox.addItem(label)
self.framework_combobox.model().item(ix).setEnabled(installed)
framework_layout.addWidget(self.framework_combobox)
layout.addLayout(framework_layout)
layout.addSpacing(10)
wdir_label = QLabel(_('Directory from which to run tests'))
layout.addWidget(wdir_label)
wdir_layout = QHBoxLayout()
self.wdir_lineedit = QLineEdit(self)
wdir_layout.addWidget(self.wdir_lineedit)
self.wdir_button = QPushButton(ima.icon('DirOpenIcon'), '', self)
self.wdir_button.setToolTip(_("Select directory"))
self.wdir_button.clicked.connect(lambda: self.select_directory())
wdir_layout.addWidget(self.wdir_button)
layout.addLayout(wdir_layout)
layout.addSpacing(20)
self.buttons = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
layout.addWidget(self.buttons)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
self.ok_button = self.buttons.button(QDialogButtonBox.Ok)
self.ok_button.setEnabled(False)
self.framework_combobox.currentIndexChanged.connect(
self.framework_changed)
self.framework_combobox.setCurrentIndex(-1)
if config.framework:
index = self.framework_combobox.findText(config.framework)
if index != -1:
self.framework_combobox.setCurrentIndex(index)
self.wdir_lineedit.setText(config.wdir)
@Slot(int)
def framework_changed(self, index):
"""Called when selected framework changes."""
if index != -1:
self.ok_button.setEnabled(True)
def select_directory(self):
"""Display dialog for user to select working directory."""
basedir = to_text_string(self.wdir_lineedit.text())
if not osp.isdir(basedir):
basedir = getcwd()
title = _("Select directory")
directory = getexistingdirectory(self, title, basedir)
if directory:
self.wdir_lineedit.setText(directory)
def get_config(self):
"""
Return the test configuration specified by the user.
Returns
-------
#.........这里部分代码省略.........
示例6: LSPServerEditor
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class LSPServerEditor(QDialog):
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 2084
DEFAULT_CMD = ''
DEFAULT_ARGS = ''
DEFAULT_CONFIGURATION = '{}'
DEFAULT_EXTERNAL = False
HOST_REGEX = re.compile(r'^\w+([.]\w+)*$')
NON_EMPTY_REGEX = re.compile(r'^\S+$')
JSON_VALID = _('JSON valid')
JSON_INVALID = _('JSON invalid')
def __init__(self, parent, language=None, cmd='', host='127.0.0.1',
port=2084, args='', external=False, configurations={},
**kwargs):
super(LSPServerEditor, self).__init__(parent)
self.parent = parent
self.external = external
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_ok = bbox.button(QDialogButtonBox.Ok)
self.button_cancel = bbox.button(QDialogButtonBox.Cancel)
self.button_ok.setEnabled(False)
description = _('To create a new configuration, '
'you need to select a programming '
'language, along with a executable '
'name for the server to execute '
'(If the instance is local), '
'and the host and port. Finally, '
'you need to provide the '
'arguments that the server accepts. '
'The placeholders <tt>%(host)s</tt> and '
'<tt>%(port)s</tt> refer to the host '
'and the port, respectively.')
server_settings_description = QLabel(description)
server_settings_description.setWordWrap(True)
lang_label = QLabel(_('Language:'))
self.lang_cb = QComboBox(self)
self.lang_cb.setToolTip(_('Programming language provided '
'by the LSP server'))
self.lang_cb.addItem(_('Select a language'))
self.lang_cb.addItems(LSP_LANGUAGES)
if language is not None:
idx = LSP_LANGUAGES.index(language)
self.lang_cb.setCurrentIndex(idx + 1)
self.button_ok.setEnabled(True)
host_label = QLabel(_('Host:'))
self.host_input = QLineEdit(self)
self.host_input.setToolTip(_('Name of the host that will provide '
'access to the server'))
self.host_input.setText(host)
self.host_input.textChanged.connect(lambda x: self.validate())
port_label = QLabel(_('Port:'))
self.port_spinner = QSpinBox(self)
self.port_spinner.setToolTip(_('TCP port number of the server'))
self.port_spinner.setMinimum(1)
self.port_spinner.setMaximum(60000)
self.port_spinner.setValue(port)
cmd_label = QLabel(_('Command to execute:'))
self.cmd_input = QLineEdit(self)
self.cmd_input.setToolTip(_('Command used to start the '
'LSP server locally'))
self.cmd_input.setText(cmd)
if not external:
self.cmd_input.textChanged.connect(lambda x: self.validate())
args_label = QLabel(_('Server arguments:'))
self.args_input = QLineEdit(self)
self.args_input.setToolTip(_('Additional arguments required to '
'start the server'))
self.args_input.setText(args)
conf_label = QLabel(_('LSP Server Configurations:'))
self.conf_input = CodeEditor(None)
self.conf_input.textChanged.connect(self.validate)
color_scheme = CONF.get('appearance', 'selected')
self.conf_input.setup_editor(
language='JSON',
color_scheme=color_scheme,
wrap=False,
edge_line=True,
highlight_current_line=True,
highlight_current_cell=True,
occurrence_highlighting=True,
auto_unindent=True,
font=get_font(),
filename='config.json')
self.conf_input.setToolTip(_('Additional LSP server configurations '
'set at runtime. JSON required'))
conf_text = '{}'
try:
conf_text = json.dumps(configurations, indent=4, sort_keys=True)
except Exception:
pass
#.........这里部分代码省略.........
示例7: CSVSettingsDialog
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class CSVSettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.settings = QSettings()
# decimal
self.decimalLabel = QLabel(self.tr("decimal:"))
self.decimalComboBox = QComboBox()
self.decimalLabel.setBuddy(self.decimalComboBox)
self.decimalComboBox.addItems([",", "."])
# separator
self.separatorLabel = QLabel(self.tr("separator:"))
self.separatorComboBox = QComboBox()
self.separatorLabel.setBuddy(self.separatorComboBox)
self.separatorComboBox.addItem("Semicolon ';'", ';')
self.separatorComboBox.addItem("Comma ','", ',')
self.separatorComboBox.addItem("Tabulator '\\t'", '\t')
self.separatorComboBox.addItem("Whitespace ' '", ' ')
# buttons
self.buttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel
)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
# layout
layout = QGridLayout()
layout.addWidget(self.decimalLabel, 0, 0)
layout.addWidget(self.decimalComboBox, 0, 1)
layout.addWidget(self.separatorLabel, 1, 0)
layout.addWidget(self.separatorComboBox, 1, 1)
layout.addWidget(self.buttons, 2, 0, 1, 2)
self.setLayout(layout)
# settings
self.decimalComboBox.setCurrentIndex(
self.decimalComboBox.findText(
self.settings.value(DECIMAL_SETTING, ","))
)
self.separatorComboBox.setCurrentIndex(
self.separatorComboBox.findData(
self.settings.value(SEPARATOR_SETTING, ";"))
)
self.setWindowTitle(self.tr("record settings"))
def accept(self):
self.settings.setValue(DECIMAL_SETTING, self.decimal)
self.settings.setValue(SEPARATOR_SETTING, self.separator)
super().accept()
# decimal property
@property
def decimal(self):
return self.decimalComboBox.currentText()
# seperator property
@property
def separator(self):
return self.separatorComboBox.itemData(
self.separatorComboBox.currentIndex())
示例8: ClassFunctionDropdown
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class ClassFunctionDropdown(Panel):
"""
Class and Function/Method Dropdowns Widget.
Parameters
----------
editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor`
The editor to act on.
"""
def __init__(self, editor):
Panel.__init__(self, editor)
self._editor = editor
self._editor.sig_cursor_position_changed.connect(
self._handle_cursor_position_change_event
)
# The layout
hbox = QHBoxLayout()
self.class_cb = QComboBox()
self.method_cb = QComboBox()
hbox.addWidget(self.class_cb)
hbox.addWidget(self.method_cb)
hbox.setSpacing(0)
hbox.setContentsMargins(0, 0, 0, 0)
self.setLayout(hbox)
# Internal data
self.folds = None
self.parents = None
self.classes = None
self.funcs = None
# Initial data for the dropdowns.
self.class_cb.addItem("<None>", 0)
self.method_cb.addItem("<None>", 0)
# Attach some events.
self.class_cb.activated.connect(self.combobox_activated)
self.method_cb.activated.connect(self.combobox_activated)
def sizeHint(self):
"""Override Qt method."""
return QSize(0, self._getVerticalSize())
def _getVerticalSize(self):
"""Get the default height of a QComboBox."""
return self.class_cb.height()
def _update_data(self):
"""Update the internal data values."""
_old = self.folds
self.folds = _get_fold_levels(self.editor)
# only update our dropdown lists if the folds have changed.
if self.folds != _old:
self.classes, self.funcs = _split_classes_and_methods(self.folds)
self.populate_dropdowns()
def populate_dropdowns(self):
self.class_cb.clear()
self.method_cb.clear()
populate(self.class_cb, self.classes)
populate(self.method_cb, self.funcs)
def combobox_activated(self):
"""Move the cursor to the selected definition."""
sender = self.sender()
data = sender.itemData(sender.currentIndex())
if isinstance(data, FoldScopeHelper):
self.editor.go_to_line(data.line + 1)
def update_selected(self, linenum):
"""Updates the dropdowns to reflect the current class and function."""
self.parents = _get_parents(self.funcs, linenum)
update_selected_cb(self.parents, self.method_cb)
self.parents = _get_parents(self.classes, linenum)
update_selected_cb(self.parents, self.class_cb)
@Slot(int, int)
def _handle_cursor_position_change_event(self, linenum, column):
self._update_data()
self.update_selected(linenum)
示例9: insert_row
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
def insert_row(self, row=-1,
title='',
sample_runs='',
sample_mass_density='N/A',
sample_chemical_formula='N/A',
packing_fraction='N/A',
align_and_focus_args={},
sample_placzek_arguments={},
normalization_placzek_arguments={}):
self.table_ui.insertRow(row)
self.set_row_height(row, COLUMN_DEFAULT_HEIGHT)
_list_ui_to_unlock = [self.table_ui]
_dimension_widgets = {'label': None, 'value': 'N/A', 'units': None}
_full_dimension_widgets = {'radius': copy.deepcopy(_dimension_widgets),
'radius2': copy.deepcopy(_dimension_widgets),
'height': copy.deepcopy(_dimension_widgets)}
_text_button = {'text': None, 'button': None}
_mass_density_options = {'value': "N/A",
"selected": False}
_mass_density_infos = {'number_density': copy.deepcopy(_mass_density_options),
'mass_density': copy.deepcopy(_mass_density_options),
'mass': copy.deepcopy(_mass_density_options),
'molecular_mass': np.NaN,
'total_number_of_atoms': np.NaN,
}
_material_infos = {'mantid_format': None,
'addie_format': None}
_mass_density_infos['mass_density']["selected"] = True
_master_table_row_ui = {'active': None,
'title': None,
'sample': {'runs': None,
'background': {'runs': None,
'background': None,
},
'material': copy.deepcopy(_text_button),
'material_infos': copy.deepcopy(_material_infos),
'mass_density': copy.deepcopy(_text_button),
'mass_density_infos': copy.deepcopy(_mass_density_infos),
'packing_fraction': None,
'geometry': copy.deepcopy(_full_dimension_widgets),
'shape': None,
'abs_correction': None,
'mult_scat_correction': None,
'inelastic_correction': None,
'placzek_button': None,
'placzek_infos': None,
},
'normalization': {'runs': None,
'background': {'runs': None,
'background': None,
},
'material': copy.deepcopy(_text_button),
'material_infos': copy.deepcopy(_material_infos),
'mass_density': copy.deepcopy(_text_button),
'mass_density_infos': copy.deepcopy(_mass_density_infos),
'packing_fraction': None,
'geometry': copy.deepcopy(_full_dimension_widgets),
'shape': None,
'abs_correction': None,
'mult_scat_correction': None,
'inelastic_correction': None,
'placzek_button': None,
'placzek_infos': None,
},
'align_and_focus_args_button': None,
'align_and_focus_args_infos': {},
}
random_key = self.generate_random_key()
self.key = random_key
# block main table events
self.table_ui.blockSignals(True)
# column 0 (active or not checkBox)
_layout = QHBoxLayout()
_widget = QCheckBox()
_widget.setCheckState(QtCore.Qt.Checked)
_widget.setEnabled(True)
_master_table_row_ui['active'] = _widget
_spacer = QSpacerItem(40, 20,
QSizePolicy.Expanding,
QSizePolicy.Minimum)
_layout.addItem(_spacer)
_layout.addWidget(_widget)
_spacer = QSpacerItem(40, 20,
QSizePolicy.Expanding,
QSizePolicy.Minimum)
_layout.addItem(_spacer)
_layout.addStretch()
_new_widget = QWidget()
_new_widget.setLayout(_layout)
_widget.stateChanged.connect(lambda state=0, key=random_key:
self.main_window.master_table_select_state_changed(state, key))
column = 0
self.table_ui.setCellWidget(row, column, _new_widget)
#.........这里部分代码省略.........
示例10: CalibrationWidget
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class CalibrationWidget(ParameterWidget):
def __init__(self, parent=None):
ParameterWidget.__init__(self, _Calibration, parent)
def _init_ui(self):
# Widgets
self._combobox = QComboBox()
self._stack = QStackedWidget()
# Layouts
layout = ParameterWidget._init_ui(self)
layout.addRow(self._combobox)
layout.addRow(self._stack)
# Register classes
self._widget_indexes = {}
for entry_point in iter_entry_points('pyhmsa_gui.spec.condition.calibration'):
widget_class = entry_point.load(require=False)
widget = widget_class()
self._combobox.addItem(widget.accessibleName().title())
self._widget_indexes[widget.CLASS] = self._stack.addWidget(widget)
widget.edited.connect(self.edited)
# Signals
self._combobox.currentIndexChanged.connect(self._on_combo_box)
self._combobox.currentIndexChanged.connect(self.edited)
return layout
def _on_combo_box(self):
# Old values
oldwidget = self._stack.currentWidget()
try:
quantity = oldwidget._txt_quantity.text()
except:
quantity = None
try:
unit = oldwidget._txt_unit.text()
except:
unit = None
# Change widget
current_index = self._combobox.currentIndex()
self._stack.setCurrentIndex(current_index)
# Update values
widget = self._stack.currentWidget()
widget._txt_quantity.setText(quantity)
widget._txt_unit.setText(unit)
def parameter(self):
return self._stack.currentWidget().calibration()
def setParameter(self, calibration):
index = self._widget_indexes[type(calibration)]
self._combobox.setCurrentIndex(index)
self._stack.setCurrentIndex(index)
self._stack.currentWidget().setParameter(calibration)
def calibration(self):
return self.parameter()
def setCalibration(self, calibration):
self.setParameter(calibration)
def setReadOnly(self, state):
ParameterWidget.setReadOnly(self, state)
self._combobox.setEnabled(not state)
self._stack.currentWidget().setReadOnly(state)
def isReadOnly(self):
return ParameterWidget.isReadOnly(self) and \
not self._combobox.isEnabled() and \
self._stack.currentWidget().isReadOnly()
def hasAcceptableInput(self):
return ParameterWidget.hasAcceptableInput(self) and \
self._stack.currentWidget().hasAcceptableInput()
示例11: MixerPanel
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class MixerPanel(QFrame):
'''A color mixer to hook up to an image.
You pass the image you the panel to operate on
and it operates on that image in place. You also
pass a callback to be called to trigger a refresh.
This callback is called every time the mixer modifies
your image.'''
def __init__(self, img):
QFrame.__init__(self)
# self.setFrameStyle(QFrame.Box | QFrame.Sunken)
self.img = img
self.mixer = ColorMixer(self.img)
self.callback = None
#---------------------------------------------------------------
# ComboBox
#---------------------------------------------------------------
self.combo_box_entries = ['RGB Color', 'HSV Color',
'Brightness/Contrast',
'Gamma',
'Gamma (Sigmoidal)']
self.combo_box = QComboBox()
for entry in self.combo_box_entries:
self.combo_box.addItem(entry)
self.combo_box.currentIndexChanged.connect(self.combo_box_changed)
#---------------------------------------------------------------
# RGB color sliders
#---------------------------------------------------------------
# radio buttons
self.rgb_add = QRadioButton('Additive')
self.rgb_mul = QRadioButton('Multiplicative')
self.rgb_mul.toggled.connect(self.rgb_radio_changed)
self.rgb_add.toggled.connect(self.rgb_radio_changed)
# sliders
rs = IntelligentSlider('R', 0.51, -255, self.rgb_changed)
gs = IntelligentSlider('G', 0.51, -255, self.rgb_changed)
bs = IntelligentSlider('B', 0.51, -255, self.rgb_changed)
self.rs = rs
self.gs = gs
self.bs = bs
self.rgb_widget = QWidget()
self.rgb_widget.layout = QGridLayout(self.rgb_widget)
self.rgb_widget.layout.addWidget(self.rgb_add, 0, 0, 1, 3)
self.rgb_widget.layout.addWidget(self.rgb_mul, 1, 0, 1, 3)
self.rgb_widget.layout.addWidget(self.rs, 2, 0)
self.rgb_widget.layout.addWidget(self.gs, 2, 1)
self.rgb_widget.layout.addWidget(self.bs, 2, 2)
#---------------------------------------------------------------
# HSV sliders
#---------------------------------------------------------------
# radio buttons
self.hsv_add = QRadioButton('Additive')
self.hsv_mul = QRadioButton('Multiplicative')
self.hsv_mul.toggled.connect(self.hsv_radio_changed)
self.hsv_mul.toggled.connect(self.hsv_radio_changed)
# sliders
hs = IntelligentSlider('H', 0.36, -180, self.hsv_changed)
ss = IntelligentSlider('S', 0.002, 0, self.hsv_changed)
vs = IntelligentSlider('V', 0.002, 0, self.hsv_changed)
self.hs = hs
self.ss = ss
self.vs = vs
self.hsv_widget = QWidget()
self.hsv_widget.layout = QGridLayout(self.hsv_widget)
self.hsv_widget.layout.addWidget(self.hsv_add, 0, 0, 1, 3)
self.hsv_widget.layout.addWidget(self.hsv_mul, 1, 0, 1, 3)
self.hsv_widget.layout.addWidget(self.hs, 2, 0)
self.hsv_widget.layout.addWidget(self.ss, 2, 1)
self.hsv_widget.layout.addWidget(self.vs, 2, 2)
#---------------------------------------------------------------
# Brightness/Contrast sliders
#---------------------------------------------------------------
# sliders
cont = IntelligentSlider('x', 0.002, 0, self.bright_changed)
bright = IntelligentSlider('+', 0.51, -255, self.bright_changed)
self.cont = cont
self.bright = bright
# layout
self.bright_widget = QWidget()
self.bright_widget.layout = QGridLayout(self.bright_widget)
self.bright_widget.layout.addWidget(self.cont, 0, 0)
self.bright_widget.layout.addWidget(self.bright, 0, 1)
#----------------------------------------------------------------------
# Gamma Slider
#----------------------------------------------------------------------
gamma = IntelligentSlider('gamma', 0.005, 0, self.gamma_changed)
self.gamma = gamma
#.........这里部分代码省略.........
示例12: SerialDialog
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class SerialDialog(QDialog):
def __init__(self, settings, parent=None):
super().__init__(parent)
self.settings = settings
self.serialports = []
# port
self.portLabel = QLabel(self.tr("COM Port:"))
self.portComboBox = QComboBox()
self.portLabel.setBuddy(self.portComboBox)
self.refresh_comports(self.portComboBox)
# baudrate
self.baudrateLabel = QLabel(self.tr("Baudrate:"))
self.baudrateComboBox = QComboBox()
self.baudrateLabel.setBuddy(self.baudrateComboBox)
for br in BAUDRATES:
self.baudrateComboBox.addItem(str(br), br)
# buttons
self.dlgbuttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal)
self.dlgbuttons.rejected.connect(self.reject)
self.dlgbuttons.accepted.connect(self.accept)
# layout
layout = QGridLayout()
layout.addWidget(self.portLabel, 0, 0)
layout.addWidget(self.portComboBox, 0, 1)
layout.addWidget(self.baudrateLabel, 1, 0)
layout.addWidget(self.baudrateComboBox, 1, 1)
layout.addWidget(self.dlgbuttons, 2, 0, 1, 2)
self.setLayout(layout)
self.setWindowTitle(self.tr("Serial Settings"))
# settings
defaults = {
PORT_SETTING: "",
BAUDRATE_SETTING: "115200"
}
self.tmp_settings = ConfigManager()
self.tmp_settings.set_defaults(defaults)
self.tmp_settings.set_many(
{key: self.settings.get(key) for key in defaults.keys()}
)
self.tmp_settings.add_handler(PORT_SETTING, self.portComboBox)
self.tmp_settings.add_handler(BAUDRATE_SETTING, self.baudrateComboBox)
def accept(self):
d = self.tmp_settings.as_dict()
self.settings.set_many(d)
super().accept()
def refresh_comports(self, combobox):
self.serialports = serial_ports()
for port in self.serialports:
combobox.addItem(port)
@property
def port(self):
return self.portComboBox.currentText()
@port.setter
def port(self, value):
if value in self.serialports:
self.portComboBox.setCurrentIndex(
self.portComboBox.findText(value))
else:
raise ValueError("serial port '%s' not available" % value)
@property
def baudrate(self):
return self.baudrateComboBox.currentData()
示例13: PyDMLogDisplay
# 需要导入模块: from qtpy.QtWidgets import QComboBox [as 别名]
# 或者: from qtpy.QtWidgets.QComboBox import addItem [as 别名]
class PyDMLogDisplay(QWidget, LogLevels):
"""
Standard display for Log Output
This widget handles instantating a ``GuiHandler`` and displaying log
messages to a ``QPlainTextEdit``. The level of the log can be changed from
inside the widget itself, allowing users to select from any of the
``.levels`` specified by the widget.
Parameters
----------
parent : QObject, optional
logname : str
Name of log to display in widget
level : logging.Level
Initial level of log display
"""
Q_ENUMS(LogLevels)
LogLevels = LogLevels
terminator = '\n'
default_format = '%(asctime)s %(message)s'
default_level = logging.INFO
def __init__(self, parent=None, logname=None, level=logging.NOTSET):
QWidget.__init__(self, parent=parent)
# Create Widgets
self.label = QLabel('Minimum displayed log level: ', parent=self)
self.combo = QComboBox(parent=self)
self.text = QPlainTextEdit(parent=self)
self.text.setReadOnly(True)
self.clear_btn = QPushButton("Clear", parent=self)
# Create layout
layout = QVBoxLayout()
level_control = QHBoxLayout()
level_control.addWidget(self.label)
level_control.addWidget(self.combo)
layout.addLayout(level_control)
layout.addWidget(self.text)
layout.addWidget(self.clear_btn)
self.setLayout(layout)
# Allow QCombobox to control log level
for log_level, value in LogLevels.as_dict().items():
self.combo.addItem(log_level, value)
self.combo.currentIndexChanged[str].connect(self.setLevel)
# Allow QPushButton to clear log text
self.clear_btn.clicked.connect(self.clear)
# Create a handler with the default format
self.handler = GuiHandler(level=level, parent=self)
self.logFormat = self.default_format
self.handler.message.connect(self.write)
# Create logger. Either as a root or given logname
self.log = None
self.level = None
self.logName = logname or ''
self.logLevel = level
self.destroyed.connect(functools.partial(logger_destroyed, self.log))
def sizeHint(self):
return QSize(400, 300)
@Property(LogLevels)
def logLevel(self):
return self.level
@logLevel.setter
def logLevel(self, level):
if level != self.level:
self.level = level
idx = self.combo.findData(level)
self.combo.setCurrentIndex(idx)
@Property(str)
def logName(self):
"""Name of associated log"""
return self.log.name
@logName.setter
def logName(self, name):
# Disconnect prior log from handler
if self.log:
self.log.removeHandler(self.handler)
# Reattach handler to new handler
self.log = logging.getLogger(name)
# Ensure that the log matches level of handler
# only if the handler level is less than the log.
if self.log.level < self.handler.level:
self.log.setLevel(self.handler.level)
# Attach preconfigured handler
self.log.addHandler(self.handler)
@Property(str)
def logFormat(self):
"""Format for log messages"""
return self.handler.formatter._fmt
@logFormat.setter
def logFormat(self, fmt):
#.........这里部分代码省略.........