Пример #1
0
    def lineEditor(self, name, item, props, parent):
        """ Creates a new editor suitable for selecting a series or index.

        @param name item parameter name, as string, to receive value updates
        @param item IndexItem instance
        @param props mapping of index class constructor properties
        @param parent ancestor of new widget
        @return QComboBox widget
        """
        children = list(item.root().children(True))
        editor = QComboBox(parent)
        editor.addItem('')
        exclude = [item.text(), self.defaultText]
        items = [c.text() for c in children if c.text() not in exclude]
        editor.addItems(items)
        try:
            editor.setCurrentIndex(editor.findText(item.parameters[name]))
        except (KeyError, ):
            item.parameters[name] = ''
        @pyqtSignature('int')
        def onChange(index):
            item.parameters[name] = str(editor.currentText())
            self.emit(Signals.modified)
        editor.onChange = onChange
        editor.connect(editor, Signals.currentIndexChanged, onChange)
        return editor
class GoogleFinanceUrlSetupDialog(QDialog):

    SETTING_GOOGLE_URL = 'googleUrl'
    SETTING_GOOGLE_COUNTRY = 'googleCountry'

    def __init__(self, parent):

        QDialog.__init__(self, parent)

        self.prop = MaeMoneyProperties.instance()
        self.urls = {}
        self.urls[self.prop.GOOGLE_COUNTRY_HK] = 'www.google.com.hk'
        self.urls[self.prop.GOOGLE_COUNTRY_CN] = 'www.google.com.cn'
        self.urls[self.prop.GOOGLE_COUNTRY_CAN] = 'www.google.ca'
        self.urls[self.prop.GOOGLE_COUNTRY_UK] = 'www.google.co.uk'
        self.urls[self.prop.GOOGLE_COUNTRY_US] = 'www.google.com'

        self.setupUi()

    def setupUi(self):
        self.setWindowModality(Qt.WindowModal)
        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)

        self.gridLayout = QGridLayout()
        self.setLayout(self.gridLayout)

        self.labelGFinanceUrl = QLabel(self.tr("Google URL"))
        self.gridLayout.addWidget(self.labelGFinanceUrl, 0, 1, 1, 1)
        self.comboBoxGFinanceUrl = QComboBox()
        for [country, url] in sorted(self.urls.iteritems()):
            self.comboBoxGFinanceUrl.addItem(country, url)

        googleCountry = self.prop.getGoogleCountry()
        index = self.comboBoxGFinanceUrl.findText(googleCountry)
        self.comboBoxGFinanceUrl.setCurrentIndex(index)
        self.gridLayout.addWidget(self.comboBoxGFinanceUrl, 0, 2, 1, 1)

        self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1)
        self.gridLayout.addWidget(QLabel(self.prop.getGoogleCountry()),
                                  1, 2, 1, 1)

        self.setUrlButton = QPushButton(self.tr("Set URL"))
        self.gridLayout.addWidget(self.setUrlButton, 2, 1, 1, 2)

        self.loginErrorMsgLabel = QLabel("")
        self.gridLayout.addWidget(self.loginErrorMsgLabel, 3, 1, 1, 2)

        self.setWindowTitle(self.tr("Setup"))

        self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.setUrlButton, SIGNAL("clicked()"), self.setUrl)

    def setUrl(self):
        indexSelected = self.comboBoxGFinanceUrl.currentIndex()
        country = self.comboBoxGFinanceUrl.itemText(indexSelected)
        url = self.comboBoxGFinanceUrl.itemData(indexSelected).toString().toAscii()
        self.prop.setGoogleCountryUrl(country, url)
        self.accept()
Пример #3
0
class EnumConfigControl(ConfigControl):
    def __init__(self, config_item):
        ConfigControl.__init__(self, config_item)

        self._init_ui()

    def _init_ui(self):
        lbl_enum = QLabel(self._config_item.tag())
        lbl_enum.setFixedWidth(self.LABEL_WIDTH)

        self._cmbo_enum = QComboBox()
        self._cmbo_enum.addItems(self._config_item.enum_names)

        selected = self._config_item.value()
        index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString)
        self._cmbo_enum.setCurrentIndex(index)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.addWidget(lbl_enum)
        hbox.addWidget(self._cmbo_enum)
        hbox.addStretch()

        self.setLayout(hbox)

    def update_from_config(self):
        selected = self._config_item.value()
        index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString)
        index = max(0, index)
        self._cmbo_enum.setCurrentIndex(index)

    def save_to_config(self):
        value = self._cmbo_enum.currentText()
        self._config_item.set(value)
Пример #4
0
class collectDelegate(QItemDelegate):

    def __init__(self, parent, module):
        self.module = module
        QItemDelegate.__init__(self, parent)

    def createEditor (self, parent, option, index):
        column = index.column()
        row = index.row()
        self.index = index
        content = index.model().data(index, Qt.EditRole)
        if column == 2:
            content = index.model().data(index, Qt.EditRole)
            label = index.model().data(index.model().index(row,1), Qt.EditRole)
            checkrowIndex = index.model().index(row,0)
            checkrowIndex = index.model().data(index.model().index(row,0), Qt.CheckStateRole)
            self.editorQWidget = QComboBox(parent)
            self.editorQWidget.setEditable(True)
            self.editorQWidget.addItems(self.module.fieldMapping.values())
            self.editorQWidget.addItems(['GEOMETRY','ODKUUID'])
            if content in self.module.fieldMapping.values():
                self.editorQWidget.setCurrentIndex(self.editorQWidget.findData(content))
                #self.module.fieldTable.item(row,0).setCheckState(Qt.Checked)
            else:
                #self.editorQWidget.insertItem(0,label)
                self.editorQWidget.insertItem(0,'')
                #self.module.fieldTable.item(row,0).setCheckState(Qt.Unchecked)
                self.editorQWidget.setCurrentIndex(0)
            return self.editorQWidget
        else:
            return None
        return QItemDelegate.createEditor(self, parent, option, index)
Пример #5
0
    def __init__(self, game):
        SelectRuleset.__init__(self)
        self.game = game
        Players.load()
        self.setWindowTitle(m18n('Select four players') + ' - Kajongg')
        self.names = None
        self.nameWidgets = []
        for idx, wind in enumerate(WINDS):
            cbName = QComboBox()
            cbName.manualSelect = False
            # increase width, we want to see the full window title
            cbName.setMinimumWidth(350)  # is this good for all platforms?
            cbName.addItems(Players.humanNames.values())
            self.grid.addWidget(cbName, idx + 1, 1)
            self.nameWidgets.append(cbName)
            self.grid.addWidget(WindLabel(wind), idx + 1, 0)
            cbName.currentIndexChanged.connect(self.slotValidate)

        query = Query(
            "select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)"
        )
        if len(query.records):
            for pidx, playerId in enumerate(query.records[0]):
                try:
                    playerName = Players.humanNames[playerId]
                    cbName = self.nameWidgets[pidx]
                    playerIdx = cbName.findText(playerName)
                    if playerIdx >= 0:
                        cbName.setCurrentIndex(playerIdx)
                except KeyError:
                    logError('database is inconsistent: player with id %d is in game but not in player' \
                               % playerId)
        self.slotValidate()
Пример #6
0
    def __init__(self, iterable=False, help_link=""):
        QWidget.__init__(self)
        self._iterable = iterable

        addHelpToWidget(self, help_link)

        layout = QHBoxLayout()

        analysis_module_combo = QComboBox()

        module_names = getAnalysisModuleNames(self._iterable)
        for module_name in module_names:
            analysis_module_combo.addItem(module_name)

        self._current_module_name = self._getCurrentAnalysisModuleName()
        if self._current_module_name is not None:
            analysis_module_combo.setCurrentIndex(
                module_names.index(self._current_module_name))

        analysis_module_combo.currentIndexChanged[int].connect(
            self.analysisModuleChanged)

        variables_popup_button = QToolButton()
        variables_popup_button.setIcon(resourceIcon("ide/small/cog_edit.png"))
        variables_popup_button.clicked.connect(self.showVariablesPopup)
        variables_popup_button.setMaximumSize(20, 20)

        layout.addWidget(analysis_module_combo, 0, Qt.AlignLeft)
        layout.addWidget(variables_popup_button, 0, Qt.AlignLeft)
        layout.setContentsMargins(QMargins(0, 0, 0, 0))
        layout.addStretch()

        self.setLayout(layout)
Пример #7
0
    def __init__(self, parent, configuration):
        QTableWidget.__init__(self, 5, 1, parent)
        self._configuration = configuration
        self._manual_change = True
        self.setVerticalHeaderLabels(
            ["Duration (cycles)", "Duration (ms)", "Cycles / ms",
             'RAM access time', 'Execution Time Model'])
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().hide()
        self.setItem(0, 0, QTableWidgetItem(str(configuration.duration)))
        self.setItem(1, 0, QTableWidgetItem(str(
            float(configuration.duration) / configuration.cycles_per_ms)))
        self.setItem(2, 0, QTableWidgetItem(str(configuration.cycles_per_ms)))
        self.setItem(
            3, 0, QTableWidgetItem(str(configuration.memory_access_time)))

        item = QComboBox(self)
        selected = 0
        for i, (etm_name, etm_code) in \
                enumerate(execution_time_model_names.items()):
            item.addItem(etm_name)
            if etm_code == configuration.etm:
                selected = i
        item.setCurrentIndex(selected)
        self.setCellWidget(4, 0, item)

        def activation_handler(x):
            configuration.etm = execution_time_model_names[str(x)]
            configuration.conf_changed()
        item.activated['QString'].connect(activation_handler)

#        self._update_observe_window()

        self.cellChanged.connect(self._cell_changed)
Пример #8
0
class EnumConfigControl(ConfigControl):
    def __init__(self, config_item):
        ConfigControl.__init__(self, config_item)

        self._init_ui()

    def _init_ui(self):
        lbl_enum = QLabel(self._config_item.tag())
        lbl_enum.setFixedWidth(self.LABEL_WIDTH)

        self._cmbo_enum = QComboBox()
        self._cmbo_enum.addItems(self._config_item.enum_names)

        selected = self._config_item.value()
        index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString)
        self._cmbo_enum.setCurrentIndex(index)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.addWidget(lbl_enum)
        hbox.addWidget(self._cmbo_enum)
        hbox.addStretch()

        self.setLayout(hbox)

    def update_from_config(self):
        selected = self._config_item.value()
        index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString)
        index = max(0, index)
        self._cmbo_enum.setCurrentIndex(index)

    def save_to_config(self):
        value = self._cmbo_enum.currentText()
        self._config_item.set(value)
Пример #9
0
    def addRow(self):
        self.tblParameters.setRowCount(self.tblParameters.rowCount() + 1)

        row = self.tblParameters.rowCount() - 1
        column = 0
        for param in self.alg.parameters:
            if param.hidden:
                continue

            self.tblParameters.setCellWidget(
                row, column, self.getWidgetFromParameter(param, row, column))
            column += 1

        for out in self.alg.outputs:
            if out.hidden:
                continue

            self.tblParameters.setCellWidget(
                row, column,
                BatchOutputSelectionPanel(out, self.alg, row, column, self))
            column += 1

        if self.alg.getVisibleOutputsCount():
            item = QComboBox()
            item.addItem(self.tr('Yes'))
            item.addItem(self.tr('No'))
            item.setCurrentIndex(0)
            self.tblParameters.setCellWidget(row, column, item)
Пример #10
0
class ComboBox(QWidget):
    def __init__(self, caption, values, default_value, caption_size=None, expand_combo=False):
        QWidget.__init__(self)

        self.values = values

        description = QLabel(caption)
        description.setWordWrap(True)
        if caption_size:
            description.setMaximumWidth(caption_size)

        self.combo = QComboBox()
        for item in values:
            self.combo.addItem(item, item)

        for i in range(0, len(values)):
            if values[i] == default_value:
                self.combo.setCurrentIndex(i)
                break

        hbox = QHBoxLayout()
        hbox.addWidget(description)
        hbox.addSpacing(10)
        if expand_combo:
            hbox.addWidget(self.combo, 1)
        else:
            hbox.addWidget(self.combo)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(0, 0, 0, 0)

    def get_value(self):
        return str(self.values[self.combo.currentIndex()])
Пример #11
0
    def __init__(self, game):
        SelectRuleset.__init__(self)
        self.game = game
        Players.load()
        self.setWindowTitle(m18n('Select four players') + ' - Kajongg')
        self.names = None
        self.nameWidgets = []
        for idx, wind in enumerate(WINDS):
            cbName = QComboBox()
            cbName.manualSelect = False
            # increase width, we want to see the full window title
            cbName.setMinimumWidth(350) # is this good for all platforms?
            cbName.addItems(Players.humanNames.values())
            self.grid.addWidget(cbName, idx+1, 1)
            self.nameWidgets.append(cbName)
            self.grid.addWidget(WindLabel(wind), idx+1, 0)
            cbName.currentIndexChanged.connect(self.slotValidate)

        query = Query("select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)")
        if len(query.records):
            for pidx, playerId in enumerate(query.records[0]):
                try:
                    playerName = Players.humanNames[playerId]
                    cbName = self.nameWidgets[pidx]
                    playerIdx = cbName.findText(playerName)
                    if playerIdx >= 0:
                        cbName.setCurrentIndex(playerIdx)
                except KeyError:
                    logError('database is inconsistent: player with id %d is in game but not in player' \
                               % playerId)
        self.slotValidate()
Пример #12
0
    def _add_task_to_table(self, row, task):
        self._ignore_cell_changed = True
        self.setItem(row, self._dict_header['id'],
                     QTableWidgetItem(str(task.identifier)))
        self.item(row, self._dict_header['id']) \
            .setTextAlignment(Qt.AlignCenter)
        self.setItem(row, self._dict_header['name'],
                     QTableWidgetItem(str(task.name)))

        combo = QComboBox()
        items = [task_type for task_type in Task.task_types_names]
        combo.addItems(items)
        # FIXME: only until I get an access to the documentation.
        for i, t in enumerate(Task.task_types_names):
            if t == task.task_type:
                combo.setCurrentIndex(i)
        combo.currentIndexChanged.connect(
            lambda x: self._cell_changed(row, self._dict_header['task_type']))
        self.setCellWidget(row, self._dict_header['task_type'], combo)

        item = QTableWidgetItem(task.abort_on_miss and 'Yes' or 'No')
        item.setFlags(
            Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        item.setCheckState(task.abort_on_miss and Qt.Checked or Qt.Unchecked)
        self.setItem(row, self._dict_header['abort'], item)

        self.setItem(row, self._dict_header['list_activation_dates'],
                     QTableWidgetItem(
                         ', '.join(map(str, task.list_activation_dates))))
        self.item(row, self._dict_header['list_activation_dates']) \
            .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

        for i in ['activation_date', 'period',
                  'deadline', 'wcet', 'base_cpi', 'n_instr', 'mix', 'acet',
                  'et_stddev', 'preemption_cost']:
            self.setItem(row, self._dict_header[i],
                         QTableWidgetItem(str(task.__dict__[i])))
            self.item(row, self._dict_header[i]) \
                .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

        stack_item = QTableWidgetItem(str(task.stack_file))
        stack_item.setFlags(stack_item.flags() ^ (Qt.ItemIsEditable))
        self.setItem(row, self._dict_header['sdp'], stack_item)

        combo = QComboBox()
        combo.currentIndexChanged.connect(
            lambda x: self._cell_changed(row, self._dict_header['followed']))
        self.setCellWidget(row, self._dict_header['followed'], combo)

        for col in range(len(self._custom_fields)):
            key = self._custom_fields[col]
            if key in task.data and task.data[key] is not None:
                item = QTableWidgetItem(str(task.data[key]))
            else:
                item = QTableWidgetItem('')
            item.setBackgroundColor(QColor.fromRgb(200, 255, 200))
            self.setItem(row, col + len(self._header), item)

        self._ignore_cell_changed = False
        self._show_period(task, row)
Пример #13
0
    def __init__(self, iterable=False, load_all = False, help_link=""):
        QWidget.__init__(self)
        self._iterable = iterable

        addHelpToWidget(self, help_link)

        layout = QHBoxLayout()

        analysis_module_combo = QComboBox()

        self._module_names = getAnalysisModuleNames(self._iterable)
        if load_all:
            self._module_names += getAnalysisModuleNames(not self._iterable)

        for module_name in self._module_names:
            analysis_module_combo.addItem(module_name)

        self._current_module_name = self._getCurrentAnalysisModuleName()
        if self._current_module_name is not None:
            analysis_module_combo.setCurrentIndex(self._module_names.index(self._current_module_name))

        analysis_module_combo.currentIndexChanged[int].connect(self.analysisModuleChanged)

        variables_popup_button = QToolButton()
        variables_popup_button.setIcon(resourceIcon("ide/small/cog_edit.png"))
        variables_popup_button.clicked.connect(self.showVariablesPopup)
        variables_popup_button.setMaximumSize(20, 20)

        layout.addWidget(analysis_module_combo, 0, Qt.AlignLeft)
        layout.addWidget(variables_popup_button, 0, Qt.AlignLeft)
        layout.setContentsMargins(QMargins(0, 0, 0, 0))
        layout.addStretch()

        self.setLayout(layout)
Пример #14
0
    def createEditor(self, parent, option, index):
        """
        Creates the combobox inside a parent.
        :param parent: The container of the combobox
        :type parent: QWidget
        :param option: QStyleOptionViewItem class is used to describe the
        parameters used to draw an item in a view widget.
        :type option: Object
        :param index: The index where the combobox
         will be added.
        :type index: QModelIndex
        :return: The combobox
        :rtype: QComboBox
        """

        if index.column() == 0:
            str_combo = QComboBox(parent)
            str_combo.insertItem(0, " ")
            for id, type in self.str_type_set_data().iteritems():
                str_combo.addItem(type, id)
            if self.str_type_id is not None:
                str_combo.setCurrentIndex(self.str_type_id)
            return str_combo
        elif index.column() == 1:

            spinbox = QDoubleSpinBox(parent)
            spinbox.setObjectName(unicode(index.row()))
            spinbox.setMinimum(0.00)
            spinbox.setSuffix('%')
            spinbox.setMaximum(100.00)
            return spinbox
Пример #15
0
    def __init__(self, parent, message, title, options, default):
        super(OptionDialog, self).__init__(parent)

        self.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        self.setIcon(QMessageBox.Question)
        self.setText(message)
        self.setWindowTitle(title)

        self.selection = default

        box = QWidget()
        box.setLayout(QGridLayout())
        box.setFixedHeight(40)

        box_combo = QWidget()
        combo = QComboBox(box_combo)
        combo.setEditable(False)
        combo.box = box_combo
        for item in options:
            combo.addItem(str(item))
        combo.setCurrentIndex(default)
        combo.currentIndexChanged.connect(self.set_selection)

        box.layout().addWidget(QLabel("Select Option"), 0, 0, 1, 1)
        box.layout().addWidget(box_combo, 0, 1, 1, 1)

        self.layout().addWidget(box, 1, 1, 1, 2)
Пример #16
0
    def addRow(self):
        self.tblParameters.setRowCount(self.tblParameters.rowCount() + 1)

        row = self.tblParameters.rowCount() - 1
        column = 0
        for param in self.alg.parameters:
            if param.hidden:
                continue

            self.tblParameters.setCellWidget(
                row, column, self.getWidgetFromParameter(param, row, column))
            column += 1

        for out in self.alg.outputs:
            if out.hidden:
                continue

            self.tblParameters.setCellWidget(
                row, column, BatchOutputSelectionPanel(
                    out, self.alg, row, column, self))
            column += 1

        if self.alg.getVisibleOutputsCount():
            item = QComboBox()
            item.addItem(self.tr('Yes'))
            item.addItem(self.tr('No'))
            item.setCurrentIndex(0)
            self.tblParameters.setCellWidget(row, column, item)
Пример #17
0
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(self.tr("Name:")), 0, 0)
        self.name = QLineEdit()
        if self._parent._item.name == '':
            self.name.setText(file_manager.get_basename(
                self._parent._item.path))
        else:
            self.name.setText(self._parent._item.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(self.tr("Project Type:")), 1, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent._item.projectType)
        grid.addWidget(self.txtType, 1, 1)
        grid.addWidget(QLabel(self.tr("Description:")), 2, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent._item.description)
        grid.addWidget(self.description, 2, 1)
        grid.addWidget(QLabel(self.tr("URL:")), 3, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent._item.url)
        grid.addWidget(self.url, 3, 1)
        grid.addWidget(QLabel(self.tr("Licence:")), 4, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        index = self.cboLicense.findText(self._parent._item.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 4, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent._item.extensions))
        grid.addWidget(QLabel(self.tr("Supported Extensions:")), 5, 0)
        grid.addWidget(self.txtExtensions, 5, 1)

        grid.addWidget(QLabel(self.tr("Indentation: ")), 6, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 6, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 6, 2)
Пример #18
0
class FontLayout(QHBoxLayout):
    """Font selection"""
    def __init__(self, value, parent=None):
        QHBoxLayout.__init__(self)
        font = tuple_to_qfont(value)
        assert font is not None

        # Font family
        self.family = QFontComboBox(parent)
        self.family.setCurrentFont(font)
        self.addWidget(self.family)

        # Font size
        self.size = QComboBox(parent)
        self.size.setEditable(True)
        sizelist = list(itertools.chain(range(6, 12), range(12, 30, 2), [36, 48, 72]))
        size = font.pointSize()
        if size not in sizelist:
            sizelist.append(size)
            sizelist.sort()
        self.size.addItems([str(s) for s in sizelist])
        self.size.setCurrentIndex(sizelist.index(size))
        self.addWidget(self.size)

    def get_font(self):
        font = self.family.currentFont()
        font.setPointSize(int(self.size.currentText()))
        return qfont_to_tuple(font)
Пример #19
0
class PageProjectProperties(QWizardPage):
    def __init__(self):
        QWizardPage.__init__(self)
        self.setTitle('New Project Data')
        self.setSubTitle(
            'Complete the following fields to create the Project Structure')

        g_box = QGridLayout(self)
        #Names of the blanks to complete
        self.lbl_Name = QLabel('New Project Name:')
        self.lbl_Place = QLabel('Project Location:')
        self.lbl_Folder = QLabel('Projet Folder:')
        self.lbl_Description = QLabel('Project Description:')
        self.lbl_License = QLabel('Project License:')
        g_box.addWidget(self.lbl_Name, 0, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Place, 1, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Folder, 2, 0, Qt.AlignRight)
        g_box.addWidget(self.lbl_Description, 3, 0, Qt.AlignTop)
        g_box.addWidget(self.lbl_License, 4, 0, Qt.AlignRight)

        #Blanks on de right of the grid
        self.txtName = QLineEdit()
        self.registerField('projectName*', self.txtName)
        #Here comes a LineEdit and a PushButton in a HBoxLayout
        h_Place = QHBoxLayout()
        self.txtPlace = QLineEdit()
        self.txtPlace.setReadOnly(True)
        self.registerField('place*', self.txtPlace)
        self.btnExamine = QPushButton('Examine...')
        h_Place.addWidget(self.txtPlace)
        h_Place.addWidget(self.btnExamine)
        #Now lets continue with the rest
        self.txtFolder = QLineEdit()
        self.txtDescription = QPlainTextEdit()
        self.cboLicense = QComboBox()
        self.cboLicense.setFixedWidth(250)
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        g_box.addWidget(self.txtName, 0, 1)
        g_box.addLayout(h_Place, 1, 1)
        g_box.addWidget(self.txtFolder, 2, 1)
        g_box.addWidget(self.txtDescription, 3, 1)
        g_box.addWidget(self.cboLicense, 4, 1)

        #Signal
        self.connect(self.btnExamine, SIGNAL('clicked()'), self.load_folder)

    def load_folder(self):
        self.txtPlace.setText(
            str(QFileDialog.getExistingDirectory(self, 'New Project Folder')))
Пример #20
0
 def OpenProjectFromFile(self, name):
     self.demands = {}
     self.project = Project()
     
     #try:
     self.project.Load(name)
     #except :
         # TODO: proper exceptioning
     #    QMessageBox.critical(self, self.tr("An error occured"), self.tr("File is not a valid project file: ") + name)
     #    return
     self.projectFile = name
     self.resourcesGraphEditor.setData(self.project.resources)
     self.ui.demands.clear()
     for d in self.project.demands:
         it = QTreeWidgetItem(self.ui.demands, QStringList([d.id, str(d.startTime), str(d.endTime), self.tr("No") if d.critical else self.tr("Yes"), self.tr("Yes") if d.assigned else self.tr("No")]))
         cb = QComboBox()
         cb.addItems([self.tr("No"),self.tr("Yes")])
         cb.setCurrentIndex(0 if d.critical else 1)
         QObject.connect(cb, SIGNAL("currentIndexChanged(int)"), it.emitDataChanged)
         self.ui.demands.setItemWidget(it,3,cb)
         it.setFlags(Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
         self.demands[it] = d
     self.UpdateRecentFiles()
     self.setWindowTitle(self.project.name + " - " + self.basename)
     self.ui.projectname.setText(self.project.name)
     self.showStats()
     self.backupTimer.start()
     self.autosaveTimer.start()
Пример #21
0
 def Translate(self, lang):
     translator = QTranslator(qApp)
     translator.load(":Translations/dc_" + lang + ".qm")
     qApp.installTranslator(translator)
     self.basename = self.tr("Data Centers GUI")
     self.demandGraphEditor.basename = self.demandGraphEditor.tr(
         "Request Graph Editor")
     self.resourcesGraphEditor.basename = self.resourcesGraphEditor.tr(
         "Resources Graph Editor")
     self.ui.retranslateUi(self)
     self.settingsDialog.ui.retranslateUi(self.settingsDialog)
     self.demandGraphEditor.ui.retranslateUi(self.demandGraphEditor)
     self.resourcesGraphEditor.ui.retranslateUi(self.resourcesGraphEditor)
     self.randomDialog.ui.retranslateUi(self.randomDialog)
     self.Vis.ui.retranslateUi(self.Vis)
     self.graphvis.ui.retranslateUi(self.graphvis)
     self.showStats()
     for k in self.demands.keys():
         cb = QComboBox()
         cb.addItems([self.tr("No"), self.tr("Yes")])
         cb.setCurrentIndex(0 if self.demands[k].critical else 1)
         QObject.connect(cb, SIGNAL("currentIndexChanged(int)"),
                         k.emitDataChanged)
         self.ui.demands.setItemWidget(k, 3, cb)
         if self.demands[k].assigned:
             k.setText(4, self.tr("Yes"))
         else:
             k.setText(4, self.tr("No"))
Пример #22
0
    def createEditor(self, parentWidget, option, index):
        #check QItemEditorFactory for help

        if index.isValid():
            sourceIndex = self.proxyModel.mapToSource(index)
            pasType = self.sourceModel.nodeFromIndex(
                sourceIndex).pasTypeOrObject
            print_debug(
                "PASParserItemDelegate.createEditor objectIndex = {0}".format(
                    pasType.objectIndex), DEBUG_MMI)
            print_debug(
                "PASParserItemDelegate.createEditor nameOfField = {0}".format(
                    pasType.nameOfField), DEBUG_MMI)
            print_debug(
                "PASParserItemDelegate.createEditor typeName    = {0}".format(
                    pasType.typeName), DEBUG_MMI)
            print_debug(
                "PASParserItemDelegate.createEditor cat         = {0}".format(
                    pasType.cat), DEBUG_MMI)

            if pasType.cat == "enum":
                comboBox = QComboBox(parentWidget)
                for enumField in pasType.enumFields:
                    comboBox.addItem(enumField)
                if pasType.arraySize == 1:
                    comboBox.setCurrentIndex(int(pasType.value, 16))
                else:
                    comboBox.setCurrentIndex(
                        int(pasType.value[sourceIndex.row()], 16))

                return comboBox
            else:
                return super(PASParserItemDelegate,
                             self).createEditor(parentWidget, option, index)
Пример #23
0
    def lineEditor(self, name, item, props, parent):
        """ Creates a new editor suitable for selecting a series or index.

        @param name item parameter name, as string, to receive value updates
        @param item IndexItem instance
        @param props mapping of index class constructor properties
        @param parent ancestor of new widget
        @return QComboBox widget
        """
        children = list(item.root().children(True))
        editor = QComboBox(parent)
        editor.addItem('')
        exclude = [item.text(), self.defaultText]
        items = [c.text() for c in children if c.text() not in exclude]
        editor.addItems(items)
        try:
            editor.setCurrentIndex(editor.findText(item.parameters[name]))
        except (KeyError, ):
            item.parameters[name] = ''

        @pyqtSignature('int')
        def onChange(index):
            item.parameters[name] = str(editor.currentText())
            self.emit(Signals.modified)

        editor.onChange = onChange
        editor.connect(editor, Signals.currentIndexChanged, onChange)
        return editor
Пример #24
0
 def Translate(self, lang):
     translator = QTranslator(qApp)
     translator.load(":Translations/dc_" + lang + ".qm")
     qApp.installTranslator(translator)
     self.basename = self.tr("Data Centers GUI")
     self.demandGraphEditor.basename = self.demandGraphEditor.tr("Request Graph Editor")
     self.resourcesGraphEditor.basename = self.resourcesGraphEditor.tr("Resources Graph Editor")
     self.ui.retranslateUi(self)
     self.settingsDialog.ui.retranslateUi(self.settingsDialog)
     self.demandGraphEditor.ui.retranslateUi(self.demandGraphEditor)
     self.resourcesGraphEditor.ui.retranslateUi(self.resourcesGraphEditor)
     self.randomDialog.ui.retranslateUi(self.randomDialog)
     self.Vis.ui.retranslateUi(self.Vis)
     self.graphvis.ui.retranslateUi(self.graphvis)
     self.showStats()
     for k in self.demands.keys():
         cb = QComboBox()
         cb.addItems([self.tr("No"),self.tr("Yes")])
         cb.setCurrentIndex(0 if self.demands[k].critical else 1)
         QObject.connect(cb, SIGNAL("currentIndexChanged(int)"), k.emitDataChanged)
         self.ui.demands.setItemWidget(k,3,cb)
         if self.demands[k].assigned:
             k.setText(4, self.tr("Yes"))
         else:
             k.setText(4, self.tr("No"))
Пример #25
0
class LateralPanel(QWidget):

    def __init__(self, parent=None):
        super(LateralPanel, self).__init__(parent)
        self.has_component = False
        self.vbox = QVBoxLayout(self)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(self.combo, self.combo.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(self.trUtf8("Select the item from the Paste "
            "History list.\nYou can Copy items into this list with: "
            "%s\nor Paste them using: %s") %
                (resources.get_shortcut("History-Copy").toString(
                    QKeySequence.NativeText),
                resources.get_shortcut("History-Paste").toString(
                    QKeySequence.NativeText)))
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        self.vbox.addLayout(hbox)

    def add_component(self, widget):
        self.vbox.insertWidget(0, widget)
        self.has_component = True

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return self.combo.currentText()
Пример #26
0
class ComboTabWidget(QWidget):
    def __init__(self, parent):
        super(ComboTabWidget, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        
        self.switchCombo = QComboBox(self)
        layout.addWidget(self.switchCombo, 0, Qt.AlignCenter)
        
        groupBox = QGroupBox(self)
        groupBoxLayout = QVBoxLayout(groupBox)
        groupBoxLayout.setSpacing(0)
        
        self.pageArea = QStackedWidget(groupBox)
        groupBoxLayout.addWidget(self.pageArea)
        
        layout.addWidget(groupBox, 1)
        
        self.switchCombo.currentIndexChanged.connect(self.pageArea.setCurrentIndex)
        
    def setTabPosition(self, tabPos):
        pass
        
    def addTab(self, w, tabText):
        self.pageArea.addWidget(w)
        self.switchCombo.addItem(tabText)
    
    def insertTab(self, pos, w, tabText):
        self.pageArea.insertWidget(pos, w)
        self.switchCombo.insertItem(pos, tabText)
        
    def removeTab(self, index=-1):
        if index < 0:
            index = self.currentIndex()
        
        w = self.pageArea.widget(index)
        
        self.pageArea.removeWidget(w)
        self.switchCombo.removeItem(index)
        
    def updateTab(self, w, tabText, index=-1):
        if index < 0:
            index = self.switchCombo.currentIndex()
        
        self.removeTab(index)
        self.insertTab(index, w, tabText)
        self.setCurrentIndex(index)
        
    def setCurrentIndex(self, index):
        self.switchCombo.setCurrentIndex(index)
        
    def widget(self, index):
        return self.pageArea.widget(index)
        
    def currentIndex(self):
        return self.switchCombo.currentIndex()
    
    def count(self):
        return self.switchCombo.count()
Пример #27
0
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 = unicode(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.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
                     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 Settings"))

    def accept(self):
        """Reimplement Qt method"""
        configurations = []
        for index in range(self.stack.count()):
            filename = unicode(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)
Пример #28
0
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 = unicode(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.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
                     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 Settings"))
        
    def accept(self):
        """Reimplement Qt method"""
        configurations = []
        for index in range(self.stack.count()):
            filename = unicode(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)
 def _getShpFieldsCombobox(self, qgisfield, selected_shpfield = None):
     '''
     Get a combobox filled with the SHP layer fields to insert in a table widget
     
     :param qgisfield: The SHP field
     :type qgisfield: QgsField
     
     :param selected_shpfield: The QGIS field to select
     :type selected_shpfield: QString, str
     
     :returns: A combobox with the QGIS layer fields
     :rtype: QWidget
     '''
     # Datatype mapping allowed while checking. For a given SHP type, several QGIS type may be allowed or compatible
     SHP_QGIS_ALLOWED_DATATYPE_MAP = [(QVariant.String, QVariant.String),
                                      (QVariant.LongLong, QVariant.LongLong),
                                      (QVariant.LongLong, QVariant.Double),
                                      (QVariant.LongLong, QVariant.String),
                                      (QVariant.Int, QVariant.Int),
                                      (QVariant.Int, QVariant.LongLong),
                                      (QVariant.Int, QVariant.Double),
                                      (QVariant.Int, QVariant.String),
                                      (QVariant.Double, QVariant.Double),
                                      (QVariant.Double, QVariant.String)]
     
     widget = QWidget()
     combobox = QComboBox()
     layout = QHBoxLayout(widget)
     layout.addWidget(combobox, 1);
     layout.setAlignment(Qt.AlignCenter);
     layout.setContentsMargins(5,0,5,0);
     widget.setLayout(layout);
     
     shplayer = self.shplayer
     shplayer_fields = shplayer.dataProvider().fields()
     
     current_item_index = 0
     selected_index = 0
     
     combobox.addItem(QCoreApplication.translate('ImportShpDialog','<None>'), None)
     current_item_index += 1
     
     for field in shplayer_fields:
         # Include only fields with compatible data type
         for shp_type, qgis_type in SHP_QGIS_ALLOWED_DATATYPE_MAP:
             if field.type() == shp_type and qgisfield.type() == qgis_type:
                 combobox.addItem(field.name(), field.name())
                 # Select field if same name
                 if field.name() == qgisfield.name() and selected_index == 0:
                     selected_index = current_item_index
                 if field.name() == selected_shpfield:
                     selected_index = current_item_index
                 current_item_index += 1
                 break;
     
     combobox.setCurrentIndex(selected_index)
     combobox.currentIndexChanged.connect(self._comboboxShpFieldIndexChanged)
     
     return widget
Пример #30
0
class Widget(QWidget):
    def __init__(self, tool):
        super(Widget, self).__init__(tool)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)
        
        self.blockCombo = QComboBox()
        self.charmap = CharMapWidget()

        layout.addWidget(self.blockCombo)
        layout.addWidget(self.charmap)

        # size policy of combo
        p = self.blockCombo.sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.Ignored)
        self.blockCombo.setSizePolicy(p)
        
        # size policy of combo popup
        p = self.blockCombo.view().sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.MinimumExpanding)
        self.blockCombo.view().setSizePolicy(p)
        
        model = listmodel.ListModel(_blocks,
            display = lambda b: b.name)
        self.blockCombo.setModel(model)
        
        # load block setting
        name = QSettings().value("charmaptool/last_block", "", type(""))
        if name:
            for i, b in enumerate(_blocks):
                if b.name == name:
                    self.blockCombo.setCurrentIndex(i)
                    break
        
        self.blockCombo.activated[int].connect(self.updateBlock)
        self.updateBlock()
        
        self.loadSettings()
        app.settingsChanged.connect(self.loadSettings)
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        font = self.font()
        family = s.value("fontfamily", "", type(""))
        if family:
            font.setFamily(family)
        self.charmap.charmap.setDisplayFont(font)
        size = s.value("fontsize", font.pointSizeF(), float)
        self.charmap.charmap.setDisplayFontSizeF(size)
    
    def updateBlock(self):
        i = self.blockCombo.currentIndex()
        if 0 <= i < len(_blocks):
            first, last, name = _blocks[i]
            self.charmap.charmap.setRange(first, last)
            QSettings().setValue("charmaptool/last_block", name)
Пример #31
0
class PageProjectProperties(QWizardPage):

    def __init__(self):
        QWizardPage.__init__(self)
        self.setTitle('New Project Data')
        self.setSubTitle('Complete the following fields to create the Project Structure')

        g_box = QGridLayout(self)
        #Names of the blanks to complete
        self.lbl_Name = QLabel('New Project Name:')
        self.lbl_Place = QLabel('Project Location:')
        self.lbl_Folder = QLabel('Projet Folder:')
        self.lbl_Description = QLabel('Project Description:')
        self.lbl_License = QLabel('Project License:')
        g_box.addWidget(self.lbl_Name, 0, 0,Qt.AlignRight)
        g_box.addWidget(self.lbl_Place, 1, 0,Qt.AlignRight)
        g_box.addWidget(self.lbl_Folder, 2, 0,Qt.AlignRight)
        g_box.addWidget(self.lbl_Description, 3, 0,Qt.AlignTop)
        g_box.addWidget(self.lbl_License, 4, 0,Qt.AlignRight)

        #Blanks on de right of the grid
        self.txtName = QLineEdit()
        self.registerField('projectName*', self.txtName)
        #Here comes a LineEdit and a PushButton in a HBoxLayout
        h_Place = QHBoxLayout()
        self.txtPlace = QLineEdit()
        self.txtPlace.setReadOnly(True)
        self.registerField('place*', self.txtPlace)
        self.btnExamine = QPushButton('Examine...')
        h_Place.addWidget(self.txtPlace)
        h_Place.addWidget(self.btnExamine)
        #Now lets continue with the rest
        self.txtFolder = QLineEdit()
        self.txtDescription = QPlainTextEdit()
        self.cboLicense = QComboBox()
        self.cboLicense.setFixedWidth(250)
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        g_box.addWidget(self.txtName, 0,1)
        g_box.addLayout(h_Place, 1, 1)
        g_box.addWidget(self.txtFolder, 2,1)
        g_box.addWidget(self.txtDescription, 3,1)
        g_box.addWidget(self.cboLicense, 4,1)

        #Signal
        self.connect(self.btnExamine, SIGNAL('clicked()'), self.load_folder)

    def load_folder(self):
        self.txtPlace.setText(str(QFileDialog.getExistingDirectory(self, 'New Project Folder')))
Пример #32
0
def create_combo_box(choice_l, index=None, choice=None):
    qcb = QComboBox()
    qcb.addItems(choice_l)
    if index:
        qcb.setCurrentIndex(index)
    elif choice:
        qcb.setCurrentIndex(choice_l.index(choice))
    return qcb
Пример #33
0
 def create_editor(self):
     w = QComboBox()
     items = self.potential_values()
     names = [o.name for o in items]
     w.addItems(names)
     if self.current_item is not None and self.current_item.name in names:
         w.setCurrentIndex(names.index(self.current_item.name))
     return w
Пример #34
0
def create_combo_box(choice_l, index=None, choice=None):
    qcb = QComboBox()
    qcb.addItems(choice_l)
    if index:
        qcb.setCurrentIndex(index)
    elif choice:
        qcb.setCurrentIndex(choice_l.index(choice))
    return qcb
Пример #35
0
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0)
        self.name = QLineEdit()
        if not len(self._parent.project.name):
            self.name.setText(file_manager.get_basename(
                self._parent.project.path))
        else:
            self.name.setText(self._parent.project.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent.project.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent.project.project_type)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent.project.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent.project.url)
        self.url.setPlaceholderText('https://www.{}.com'.format(getuser()))
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItems(LICENCES)
        self.cboLicense.setCurrentIndex(12)
        index = self.cboLicense.findText(self._parent.project.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent.project.extensions))
        grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent.project.indentation)
        self.spinIndentation.setRange(2, 10)
        self.spinIndentation.setValue(4)
        self.spinIndentation.setSingleStep(2)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS)
        self.checkUseTabs.setChecked(self._parent.project.use_tabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Пример #36
0
    def _add_task_to_table(self, row, task):
        self._ignore_cell_changed = True
        self.setItem(row, self._dict_header['id'],
                     QTableWidgetItem(str(task.identifier)))
        self.item(row, self._dict_header['id']) \
            .setTextAlignment(Qt.AlignCenter)
        self.setItem(row, self._dict_header['name'],
                     QTableWidgetItem(str(task.name)))

        combo = QComboBox()
        items = [task_type for task_type in Task.task_types_names]
        combo.addItems(items)
        combo.setCurrentIndex(combo.findText(task.task_type))
        combo.currentIndexChanged.connect(
            lambda x: self._cell_changed(row, self._dict_header['task_type']))
        self.setCellWidget(row, self._dict_header['task_type'], combo)

        item = QTableWidgetItem(task.abort_on_miss and 'Yes' or 'No')
        item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                      | Qt.ItemIsSelectable)
        item.setCheckState(task.abort_on_miss and Qt.Checked or Qt.Unchecked)
        self.setItem(row, self._dict_header['abort'], item)

        self.setItem(
            row, self._dict_header['list_activation_dates'],
            QTableWidgetItem(', '.join(map(str, task.list_activation_dates))))
        self.item(row, self._dict_header['list_activation_dates']) \
            .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

        for i in [
                'activation_date', 'period', 'deadline', 'wcet', 'base_cpi',
                'n_instr', 'mix', 'acet', 'et_stddev', 'preemption_cost'
        ]:
            self.setItem(row, self._dict_header[i],
                         QTableWidgetItem(str(task.__dict__[i])))
            self.item(row, self._dict_header[i]) \
                .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)

        stack_item = QTableWidgetItem(str(task.stack_file))
        stack_item.setFlags(stack_item.flags() ^ (Qt.ItemIsEditable))
        self.setItem(row, self._dict_header['sdp'], stack_item)

        combo = QComboBox()
        combo.currentIndexChanged.connect(
            lambda x: self._cell_changed(row, self._dict_header['followed']))
        self.setCellWidget(row, self._dict_header['followed'], combo)

        for col in range(len(self._custom_fields)):
            key = self._custom_fields[col]
            if key in task.data and task.data[key] is not None:
                item = QTableWidgetItem(str(task.data[key]))
            else:
                item = QTableWidgetItem('')
            item.setBackgroundColor(QColor.fromRgb(200, 255, 200))
            self.setItem(row, col + len(self._header), item)

        self._ignore_cell_changed = False
        self._show_period(task, row)
Пример #37
0
class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble):
            self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)

        self.spnPrecision = QSpinBox(self)
        self.spnPrecision.setMinimum(0)
        self.spnPrecision.setMaximum(12)
        if column is not None:
            self.spnPrecision.setValue(column.formatter.precision)
        else:
            self.spnPrecision.setValue(6)

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(4)

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)

    @property
    def _valueCodec(self):
        c = valuecodecs.FloatCodec()
        c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        return c

    @property
    def _formatter(self):
        f = formatters.FloatFormatter()
        f.precision = self.spnPrecision.value()
        return f

    def createColumnModel(self, hex_widget):
        return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()
Пример #38
0
class StartSession(preferences.Group):
    def __init__(self, page):
        super(StartSession, self).__init__(page)

        grid = QGridLayout()
        self.setLayout(grid)

        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.custom.isChecked())

        self.none = QRadioButton(toggled=changed)
        self.lastused = QRadioButton(toggled=changed)
        self.custom = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)

        grid.addWidget(self.none, 0, 0, 1, 2)
        grid.addWidget(self.lastused, 1, 0, 1, 2)
        grid.addWidget(self.custom, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(
            _("Session to load if Frescobaldi is started without arguments"))
        self.none.setText(_("Start with no session"))
        self.lastused.setText(_("Start with last used session"))
        self.custom.setText(_("Start with session:"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("session")
        startup = s.value("startup", "none", type(""))
        if startup == "lastused":
            self.lastused.setChecked(True)
        elif startup == "custom":
            self.custom.setChecked(True)
        else:
            self.none.setChecked(True)
        sessionNames = sessions.sessionNames()
        self.combo.clear()
        self.combo.addItems(sessionNames)
        custom = s.value("custom", "", type(""))
        if custom in sessionNames:
            self.combo.setCurrentIndex(sessionNames.index(custom))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("session")
        s.setValue("custom", self.combo.currentText())
        if self.custom.isChecked():
            startup = "custom"
        elif self.lastused.isChecked():
            startup = "lastused"
        else:
            startup = "none"
        s.setValue("startup", startup)
Пример #39
0
class DropDownRadioBooleanFilter(QWidget, Control):
    """Container for multiple boolean filters
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QHBoxLayout())
        self.cb = QComboBox(self)

        self.layout().addWidget(self.cb)

        rblayout = QVBoxLayout()
        self.radioButtons = [QRadioButton("Only", self),
                             QRadioButton("Excluded", self)
                             ]

        for b in self.radioButtons:
            rblayout.addWidget(b)

        self.radioButtons[0].setChecked(True)

        self.layout().addLayout(rblayout)

        self.options = []

        self.setOptions(tree.subelements_top("Option"))

    def setOptions(self, options):
        self.cb.clear()
        self.options = []
        for option in options:
            self.cb.addItem(option.displayName)
            self.options.append(option)

        for op, rb in zip(self.options[0].subelements_top("Option"),
                          self.radioButtons):
            rb.setText(op.displayName)
            rb.setChecked(getattr(op, "default", "false") == "true")

    def value(self):
        return {"excluded": "0" if self.radioButtons[0].isChecked() else "1"}

    def query(self):
        filter = self.options[self.cb.currentIndex()]
        filter = biomart.FilterDescription(
            self.tree.registry, "FilterDescription",
            filter.attributes, filter.children)
        return [("Filter", filter, self.value())]

    def setControlValue(self, name, value):
        for i, option in enumerate(self.options):
            if option.internalName == name:
                self.cb.setCurrentIndex(i)
                if value == "Only":
                    self.radioButtons[0].setChecked(True)
Пример #40
0
class ProjectData(QWidget):
    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0)
        self.name = QLineEdit()
        if not len(self._parent.project.name):
            self.name.setText(
                file_manager.get_basename(self._parent.project.path))
        else:
            self.name.setText(self._parent.project.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent.project.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent.project.project_type)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent.project.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent.project.url)
        self.url.setPlaceholderText('https://www.{}.com'.format(getuser()))
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItems(LICENCES)
        self.cboLicense.setCurrentIndex(12)
        index = self.cboLicense.findText(self._parent.project.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent.project.extensions))
        grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent.project.indentation)
        self.spinIndentation.setRange(2, 10)
        self.spinIndentation.setValue(4)
        self.spinIndentation.setSingleStep(2)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS)
        self.checkUseTabs.setChecked(self._parent.project.use_tabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Пример #41
0
class configWidget(QWidget):

    def __init__(self, parent=None):
        super(configWidget, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle('LoL Server Status - Config')
        self.setMinimumWidth(parent.width())
        self.move(parent.pos())
        self.setFocus(False)

        #label_title
        label_title = QLabel('Configurations')
        label_title.setObjectName('label_title')
        label_title.setAlignment(Qt.AlignCenter)

        #combo_update_time
        self.combo_update_time = QComboBox()
        for item in ("1 minute", "2 minutes", "5 minutes", "10 minutes",
                     "20 minutes"):
            self.combo_update_time.addItem(item)

        #LAYOUTS
        #layout_update_time
        layout_update_time = QHBoxLayout()
        layout_update_time.addWidget(QLabel('Update time:'))
        layout_update_time.addWidget(self.combo_update_time)

        #General layout
        vbox = QVBoxLayout(self)
        vbox.addWidget(label_title)  # Add label_title
        vbox.addLayout(layout_update_time)  # Add layout_update_time

        self.load_config()

    def save_config(self):
        """This function save settings"""

        qsettings = QSettings()
        qsettings.setValue('configs/update_time',
                           self.combo_update_time.currentIndex())

    def load_config(self):
        """This function load settings"""

        qsettings = QSettings()
        self.combo_update_time.setCurrentIndex(
                    qsettings.value('configs/update_time', 0, type=int))

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.save_config()
            self.close()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.save_config()
            self.close()
Пример #42
0
 def createEditor (self, parent, option, index):
     try:
         content = index.model().data(index, Qt.EditRole)
         if content == None:
             return None
     except:
         return None
     column = index.column()
     row = index.row()
     parentNode = index.model().data(index.parent(), Qt.EditRole)
     self.currentIndex = index
     
     q_type = QVariant.nameToType(index.model().data(index.sibling(0,7), Qt.DisplayRole))
     if column == 1 and parentNode:  # combobox for field mapping
         currentLayer = self.iface.legendInterface().currentLayer()
         editorQWidget = QComboBox(parent)
         fieldItems = []
         for field in self.iface.legendInterface().currentLayer().pendingFields():
             fieldItems.append(field.name())
         if not content in fieldItems:
             fieldItems.append(content)
         editorQWidget.addItems(fieldItems)
         editorQWidget.setCurrentIndex(editorQWidget.findText(content))
         return editorQWidget
     if column == 3 and parentNode: # combobox for odk types
         editorQWidget = QComboBox(parent)
         #QVariantType = indexQModelIndex.model().item(row,7).data()
         if content in ['text','note','image','barcode','audio','video']:
             combobox_items = ['text','note','image','barcode','audio','video','select one']
         elif content in ['date', 'datetime']:
             combobox_items = ['date', 'time', 'datetime']
         elif content in ['geopoint','geoshape','geotrace']:
             combobox_items = ['geopoint','geoshape','geotrace']
         elif content in ['select one']:
             combobox_items = ['select one', QVariantToODKtype(q_type)]
         elif content in ['select type']:
             combobox_items = ['text','decimal','integer','date','time','datetime','geopoint','geoshape','geotrace','image','barcode','audio','video','select one']
         else:
             combobox_items = [content,'select one']
         editorQWidget.addItems(combobox_items)
         editorQWidget.setCurrentIndex(editorQWidget.findText(content))
         editorQWidget.currentIndexChanged.connect(self.changeAppearanceAccordingly)
         return editorQWidget
     elif column == 9 and parentNode: # qdialog for value/label map
         content = QgisODKChoices.getChoices(content, q_type, title = parentNode)
         index.model().setData(index,content, Qt.DisplayRole)
         QItemDelegate.createEditor(self, parent, option, index)
     elif column == 10 and parentNode: # combobox for appearance
         contentType = index.model().data(index.sibling(0,3), Qt.DisplayRole)
         if contentType == '' or not contentType in appearanceDef.keys():
             return
         editorQWidget = QComboBox(parent)
         editorQWidget.addItems(appearanceDef[contentType])
         #editorQWidget.setCurrentIndex(0)
         return editorQWidget
     else:
         return QItemDelegate.createEditor(self, parent, option, index)
Пример #43
0
class StartSession(preferences.Group):
    def __init__(self, page):
        super(StartSession, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.custom.isChecked())
        
        self.none = QRadioButton(toggled=changed)
        self.lastused = QRadioButton(toggled=changed)
        self.custom = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)
        
        grid.addWidget(self.none, 0, 0, 1, 2)
        grid.addWidget(self.lastused, 1, 0, 1, 2)
        grid.addWidget(self.custom, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)

        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Session to load if Frescobaldi is started without arguments"))
        self.none.setText(_("Start with no session"))
        self.lastused.setText(_("Start with last used session"))
        self.custom.setText(_("Start with session:"))
        
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("session")
        startup = s.value("startup", "none", type(""))
        if startup ==  "lastused":
            self.lastused.setChecked(True)
        elif startup == "custom":
            self.custom.setChecked(True)
        else:
            self.none.setChecked(True)
        sessionNames = sessions.sessionNames()
        self.combo.clear()
        self.combo.addItems(sessionNames)
        custom = s.value("custom", "", type(""))
        if custom in sessionNames:
            self.combo.setCurrentIndex(sessionNames.index(custom))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("session")
        s.setValue("custom", self.combo.currentText())
        if self.custom.isChecked():
            startup = "custom"
        elif self.lastused.isChecked():
            startup = "lastused"
        else:
            startup = "none"
        s.setValue("startup", startup)
Пример #44
0
class LilyPondPreferences(QGroupBox):
    def __init__(self, parent):
        super(LilyPondPreferences, self).__init__(parent)

        grid = QGridLayout()
        self.setLayout(grid)

        self.pitchLanguageLabel = QLabel()
        self.pitchLanguage = QComboBox()
        self.versionLabel = QLabel()
        self.version = QComboBox(editable=True)

        self.pitchLanguage.addItem('')
        self.pitchLanguage.addItems(
            [lang.title() for lang in sorted(scoreproperties.keyNames)])
        self.version.addItem(lilypondinfo.preferred().versionString())
        for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"):
            if v != lilypondinfo.preferred().versionString():
                self.version.addItem(v)

        grid.addWidget(self.pitchLanguageLabel, 0, 0)
        grid.addWidget(self.pitchLanguage, 0, 1)
        grid.addWidget(self.versionLabel, 1, 0)
        grid.addWidget(self.version, 1, 1)

        self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged)
        app.translateUI(self)
        self.loadSettings()
        self.window().finished.connect(self.saveSettings)

    def translateUI(self):
        self.setTitle(_("LilyPond"))
        self.pitchLanguageLabel.setText(_("Pitch name language:"))
        self.pitchLanguage.setToolTip(
            _("The LilyPond language you want to use for the pitch names."))
        self.pitchLanguage.setItemText(0, _("Default"))
        self.versionLabel.setText(_("Version:"))
        self.version.setToolTip(
            _("The LilyPond version you will be using for this document."))

    def slotPitchLanguageChanged(self, index):
        if index == 0:
            language = ''
        else:
            language = self.pitchLanguage.currentText().lower()
        self.window().setPitchLanguage(language)

    def loadSettings(self):
        language = self.window().pitchLanguage()
        languages = list(sorted(scoreproperties.keyNames))
        index = languages.index(language) + 1 if language in languages else 0
        self.pitchLanguage.setCurrentIndex(index)

    def saveSettings(self):
        QSettings().setValue('scorewiz/lilypond/pitch_language',
                             self.window().pitchLanguage())
Пример #45
0
class InterfacePage(QWizardPage):
    """
    Allows the user to choose one among networkable interfaces to build a net upon.
    """
    def __init__(self, parent=None):
        QWizardPage.__init__(self, parent)
        self.__make_gui()
        self.__populate()
        self.connect(self.__dropdown, SIGNAL("currentIndexChanged(int)"), self.propagate)

    def __make_gui(self):
        self.setTitle(tr("Network Editor"))
        self.setSubTitle(tr("Select the interface to which you want to add a network"))
        box = QVBoxLayout(self)
        self.__dropdown = QComboBox()
        box.addWidget(self.__dropdown)

    def __candidates(self):
        candidates = list(
            QNetObject.getInstance().netcfg.iterNetworkables()
            )
        candidates.sort()
        return candidates

    def __populate(self):
        candidates = self.__candidates()
        for interface in candidates:
            variant = QVariant(interface)
            self.__dropdown.addItem(interface.fullName(), variant)

    def propagate(self):
        """
        propagate: emits a "changed" SIGNAL with the chosen interface as content
        """
        self.emit(SIGNAL("changed"), self.interface())

    def interface(self):
        """
        returns the currently selected interface
        """
        #QVariant with custom content
        variant = self.__dropdown.itemData(
            self.__dropdown.currentIndex()
            )
        interface = variant.toPyObject()
        return interface

    def setInterface(self, target):
        for index in xrange(self.__dropdown.count()):
            variant = self.__dropdown.itemData(index)
            interface = variant.toPyObject()
            if interface is target:
                break
        self.__dropdown.setCurrentIndex(index)
Пример #46
0
class LilyPondPreferences(QGroupBox):
    def __init__(self, parent):
        super(LilyPondPreferences, self).__init__(parent)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        self.pitchLanguageLabel = QLabel()
        self.pitchLanguage = QComboBox()
        self.versionLabel = QLabel()
        self.version = QComboBox(editable=True)
        
        self.pitchLanguage.addItem('')
        self.pitchLanguage.addItems([lang.title() for lang in sorted(scoreproperties.keyNames)])
        self.version.addItem(lilypondinfo.preferred().versionString())
        for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"):
            if v != lilypondinfo.preferred().versionString():
                self.version.addItem(v)
        
        grid.addWidget(self.pitchLanguageLabel, 0, 0)
        grid.addWidget(self.pitchLanguage, 0, 1)
        grid.addWidget(self.versionLabel, 1, 0)
        grid.addWidget(self.version, 1, 1)
        
        self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged)
        app.translateUI(self)
        self.loadSettings()
        self.window().finished.connect(self.saveSettings)

    def translateUI(self):
        self.setTitle(_("LilyPond"))
        self.pitchLanguageLabel.setText(_("Pitch name language:"))
        self.pitchLanguage.setToolTip(_(
            "The LilyPond language you want to use for the pitch names."))
        self.pitchLanguage.setItemText(0, _("Default"))
        self.versionLabel.setText(_("Version:"))
        self.version.setToolTip(_(
            "The LilyPond version you will be using for this document."))

    def slotPitchLanguageChanged(self, index):
        if index == 0:
            language = ''
        else:
            language = self.pitchLanguage.currentText().lower()
        self.window().setPitchLanguage(language)
        
    def loadSettings(self):
        language = self.window().pitchLanguage()
        languages = list(sorted(scoreproperties.keyNames))
        index = languages.index(language) + 1 if language in languages else 0
        self.pitchLanguage.setCurrentIndex(index)

    def saveSettings(self):
        QSettings().setValue('scorewiz/lilypond/pitch_language', self.window().pitchLanguage())
Пример #47
0
class DisplayContainer(QWidget, DisplayContainerGeneric):
    def __init__(self, main):
        QWidget.__init__(self)
        DisplayContainerGeneric.__init__(self)
        self._main = main
        vbox = QVBoxLayout(self)
        self.stack = StackedWidget()

        vbox.addWidget(self.stack)
        self._console = ConsoleWidget()
        self.stack.addWidget(self._console)

        self.runWidget = RunWidget()
        self.stack.addWidget(self.runWidget)

        self.web = WebRender()
        self.stack.addWidget(self.web)

        self.combo = QComboBox()
        self.combo.addItem(QIcon(resources.images['console']), '')
        self.combo.addItem(QIcon(resources.images['play']), '')
        self.combo.addItem(QIcon(resources.images['web']), '')
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
                     self._item_changed)

    def gain_focus(self):
        self._console.setFocus()

    @pyqtSignature('int')
    def _item_changed(self, val):
        if not self.isVisible():
            self._main.containerIsVisible = True
            self.show()
        self.stack.show_display(val)

    def load_toolbar(self, toolbar):
        toolbar.addSeparator()
        toolbar.addWidget(self.combo)

    def run_application(self, fileName, pythonPath=False):
        self.combo.setCurrentIndex(1)
        self.runWidget.start_process(fileName, pythonPath)

    def kill_application(self):
        self.runWidget.kill_process()

    def render_web_page(self, url):
        self.combo.setCurrentIndex(2)
        self.web.render_page(url)

    def add_to_stack(self, widget, icon):
        self.stack.addWidget(widget)
        self.combo.addItem(QIcon(icon), '')
Пример #48
0
    def combo_box(self, selected, items=["None", "Happy", "Concentrated", "Bored", "Annoyed", "Angry"]):
        """ Returns a combo box of the available emotions.
        """
        combo = QComboBox()
        combo.setStyleSheet("QComboBox { combobox-popup: 0; }")
        combo.addItems(items)

        if selected in items:
            combo.setCurrentIndex(items.index(selected))

        combo.resize(300, 30)
        return combo
Пример #49
0
class resampleDialog(QDialog):
    def __init__(self, parent, multipleSelection, currSampRate):
        QDialog.__init__(self, parent)

        self.currLocale = self.parent().prm['data']['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        grid = QGridLayout()
        n = 0
        if multipleSelection == False:
            currSampRateLabel = QLabel(self.currLocale.toString(currSampRate)) 
            grid.addWidget(currSampRateLabel, n, 0)
            n = n+1
        newSampRateLabel = QLabel(self.tr('New Sampling Rate: '))
        grid.addWidget(newSampRateLabel, n, 0)
        self.newSampRateWidget = QLineEdit('48000')
        self.newSampRateWidget.setValidator(QIntValidator(self))
        grid.addWidget(self.newSampRateWidget, n, 1)
        self.newSampRateWidget.editingFinished.connect(self.onSampRateChanged)
        n = n+1

        convertorLabel = QLabel(self.tr('Resampling Algorithm: '))
        grid.addWidget(convertorLabel, n, 0)
        self.convertorChooser = QComboBox()
        self.convertorChooser.addItems(['fourier'])
        self.convertorChooser.setCurrentIndex(0)
        grid.addWidget(self.convertorChooser, n, 1)

        n = n+1

        winLabel = QLabel(self.tr('Window Type: '))
        grid.addWidget(winLabel, n, 0)
        self.winChooser = QComboBox()
        self.winChooser.addItems(self.parent().prm['data']['available_windows'])
        self.winChooser.setCurrentIndex(self.winChooser.findText(self.parent().prm['pref']['smoothingWindow']))
        grid.addWidget(self.winChooser, n, 1)

        n = n+1
        
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        grid.addWidget(buttonBox, n, 1)
        self.setLayout(grid)
        self.setWindowTitle(self.tr("Resample"))

    def onSampRateChanged(self):
        newSampRate = int(self.newSampRateWidget.text())
        if newSampRate < 1:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('New sampling rate too small'))
        else:
            self.newSampRate = newSampRate
Пример #50
0
class OptionsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._langs = get_langs()
        self._lang_selection = QComboBox()

        langs = list(self._langs.keys())
        langs.sort()

        i = 0
        lang_index = None
        for lang in langs:
            self._lang_selection.addItem(lang)
            if self._langs[lang] == get('Global', 'lang'):
                lang_index = i

            i += 1

        try:
            self._lang_selection.setCurrentIndex(lang_index)
        except TypeError:
            pass

        langBox = QHBoxLayout()
        langBox.addWidget(QLabel(_('OptionsDialog.lang')))
        langBox.addStretch(1)
        langBox.addWidget(self._lang_selection)

        cancelButton = QPushButton(_('cancel'))
        cancelButton.clicked.connect(self.reject)

        okButton = QPushButton(_('OK'))
        okButton.clicked.connect(self.accept)

        buttonBox = QHBoxLayout()
        buttonBox.addStretch(1)
        buttonBox.addWidget(cancelButton)
        buttonBox.addWidget(okButton)

        layout = QVBoxLayout()
        layout.addLayout(langBox)
        layout.addLayout(buttonBox)

        self.accepted.connect(self._save)

        self.setLayout(layout)
        self.setWindowTitle(_('OptionsDialog.title'))

    def _save(self):
        set_lang(self._langs[self._lang_selection.currentText()])
Пример #51
0
 def add_combo_box( self, choicesL, index_init=0, name='cycle_desc',
                     advance_n=True, fulldesc='Select Engine Cycle', 
                     text_align='right', text_font=ARIAL_10, col=0, width=100,
                     parent=None, layout=None):
                    
     # if parent is input, add widget to parent
     if parent is None:
         parent = self
     
     
     if layout is None:
         NRow = parent.get_next_row_number(advance_n)
     
     lbl = QLabel("    %s "%fulldesc, parent)
     combo_box = QComboBox(parent)    
     lbl.setFont( text_font )
     combo_box.setFont( text_font )
     
     self.objectD['%s_combo_box'%name] = combo_box
     for choice in choicesL:
         combo_box.addItem(choice)
     combo_box.setCurrentIndex(index_init)
     if layout is None:
         parent.grid.addWidget(lbl,      NRow, col)
     else:
         layout.addWidget( lbl )
     
     
         
     hbox = QHBoxLayout()
     hbox.addWidget(combo_box)
     hbox.addStretch(1)
     widget = QWidget()
     widget.setLayout(hbox)
     
     if layout is None:
         parent.grid.addWidget(widget, NRow, col+1)
     
         if text_align=='right':
             parent.grid.setAlignment(lbl, Qt.AlignRight )
     else:
         layout.addWidget( widget )
     
     combo_box.setFixedWidth( width )
         
     combo_box.activated[str].connect( lambda: self.combo_box_changed( '%s_combo_box'%name ) )   
         
     self.input_widget_by_nameD[name] = (combo_box, 'combo_box')
Пример #52
0
class FontLayout(QGridLayout):
    """Font selection"""
    def __init__(self, value, parent=None):
        QGridLayout.__init__(self)
        font = tuple_to_qfont(value)
        assert font is not None

        # Font family
        self.family = QFontComboBox(parent)
        self.addWidget(self.family, 0, 0, 1, -1)

        # Font size
        self.size = QComboBox(parent)
        self.size.setEditable(True)
        sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72]
        size = font.pointSize()
        if size not in sizelist:
            sizelist.append(size)
            sizelist.sort()
        self.size.addItems([str(s) for s in sizelist])
        self.addWidget(self.size, 1, 0)

        # Italic or not
        self.italic = QCheckBox(self.tr("Italic"), parent)
        self.addWidget(self.italic, 1, 1)

        # Bold or not
        self.bold = QCheckBox(self.tr("Bold"), parent)
        self.addWidget(self.bold, 1, 2)
        self.set_font(font)

    def set_font(self, font):
        self.family.setCurrentFont(font)
        size = font.pointSize()
        i = self.size.findText(str(size))
        if i >= 0:
            self.size.setCurrentIndex(i)
        self.italic.setChecked(font.italic())
        self.bold.setChecked(font.bold())

    def get_font(self):
        font = self.family.currentFont()
        font.setItalic(self.italic.isChecked())
        font.setBold(self.bold.isChecked())
        font.setPointSize(int(self.size.currentText()))
        return qfont_to_tuple(font)
Пример #53
0
class DropDownIdListFilter(QWidget, Control):

    """Container for multiple id list filters
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QVBoxLayout())
        self.setContentsMargins(0, 0, 0, 0)
        self.cb = QComboBox()
        self.idsEdit = QPlainTextEdit()

        self.layout().addWidget(self.cb)
        self.layout().addWidget(self.idsEdit)

        self.options = []
        self.setOptions(tree.subelements_top("Option"))

    def setOptions(self, options):
        self.cb.clear()
        self.options = []
        for option in options:
            self.cb.addItem(option.displayName)
            self.options.append(option)

    def value(self):
        return str(self.idsEdit.toPlainText()).split()

    def query(self):
        filter = self.options[self.cb.currentIndex()]
        filter = biomart.FilterDescription(
            self.tree.registry, "FilterDescription",
            filter.attributes, filter.children)
        return [("Filter", filter, self.value())]

    def setControlValue(self, name, value):
        if isinstance(value, list):
            value = "\n".join(value)

        for i, op in enumerate(self.options):
            if name == op.internalName:
                self.cb.setCurrentIndex(i)
                self.idsEdit.setPlainText(value)
Пример #54
0
class LateralPanel(QWidget):
    def __init__(self, parent=None):
        super(LateralPanel, self).__init__(parent)
        self.has_component = False
        self.vbox = QVBoxLayout(self)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.labelText = "Ln: %s, Col: %s"
        self.labelCursorPosition = QLabel(self.trUtf8(self.labelText % (0, 0)))
        hbox.addWidget(self.labelCursorPosition)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(
            self.combo, self.combo.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(
            self.trUtf8(
                "Select the item from the Paste "
                "Historial list.\nYou can Copy items into this list with: "
                "%s\nor Paste them using: %s") %
            (resources.get_shortcut("History-Copy").toString(
                QKeySequence.NativeText),
             resources.get_shortcut("History-Paste").toString(
                 QKeySequence.NativeText)))
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        self.vbox.addLayout(hbox)

    def add_component(self, widget):
        self.vbox.insertWidget(0, widget)
        self.has_component = True

    def update_line_col(self, line, col):
        self.labelCursorPosition.setText(
            self.trUtf8(self.labelText % (line, col)))

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return self.combo.currentText()
    def _getCombobox(self,
                     values,
                     primary_selected_value=None,
                     secondary_selected_value=None,
                     currentindex_changed_callback=None):
        '''
        Get a combobox filled with the given values
        
        :param values: The values as key = value, value = description or text
        :type values: Dict
        
        :returns: A combobox
        :rtype: QWidget
        '''

        widget = QWidget()
        combobox = QComboBox()
        layout = QHBoxLayout(widget)
        layout.addWidget(combobox, 1)
        layout.setAlignment(Qt.AlignCenter)
        layout.setContentsMargins(5, 0, 5, 0)
        widget.setLayout(layout)

        current_item_index = 0
        selected_index = 0

        for key, value in values.iteritems():
            combobox.addItem(value, key)

            # Select value
            if key == secondary_selected_value and selected_index == 0:
                selected_index = current_item_index
            if key == primary_selected_value:
                selected_index = current_item_index

            current_item_index += 1

        combobox.setCurrentIndex(selected_index)

        if currentindex_changed_callback is not None:
            combobox.currentIndexChanged.connect(currentindex_changed_callback)

        return widget
Пример #56
0
class cutDialog(QDialog):
    def __init__(self, parent, snd):
        QDialog.__init__(self, parent)

        self.currLocale = self.parent().prm['data']['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        grid = QGridLayout()
        n = 0

        fromLabel = QLabel(self.tr('From: '))
        grid.addWidget(fromLabel, n, 0)
        self.fromWidget = QLineEdit('0')
        self.fromWidget.setValidator(QDoubleValidator(self))
        grid.addWidget(self.fromWidget, n, 1)

        unitLabel = QLabel(self.tr('Unit: '))
        grid.addWidget(unitLabel, n, 2)
        self.unitChooser = QComboBox()
        self.unitChooser.addItems(
            [self.tr("Seconds"),
             self.tr("Milliseconds"),
             self.tr("Samples")])
        self.unitChooser.setCurrentIndex(0)
        grid.addWidget(self.unitChooser, n, 3)

        n = n + 1
        toLabel = QLabel(self.tr('To: '))
        grid.addWidget(toLabel, n, 0)
        self.toWidget = QLineEdit('0')
        self.toWidget.setValidator(QDoubleValidator(self))
        grid.addWidget(self.toWidget, n, 1)
        n = n + 1

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        grid.addWidget(buttonBox, n, 3)
        self.setLayout(grid)
        self.setWindowTitle(self.tr("Cut"))