Python PyQt5.QtCore.QVariant() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QVariant(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .

Example 1
Project: KStock   Author: aseylys   File: ObjList.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setData(self, index, value, role = Qt.EditRole):
        if not index.isValid():
            return False
        obj = self.getObject(index)
        prop = self.getProperty(index)
        if (obj is None) or (prop is None):
            return None
        try:
            action = prop.get('action', None)
            if action is not None:
                if action == "button":
                    getAttrRecursive(obj, prop['attr'])()  # Call obj.attr()
                    return True
                elif action == "fileDialog":
                    pass  # File loading handled via @property.setter obj.attr below. Otherwise just sets the file name text.
            if role == Qt.EditRole:
                if type(value) == QVariant:
                    value = value.toPyObject()
                if (QT_VERSION_STR[0] == '4') and (type(value) == QString):
                    value = str(value)
                setAttrRecursive(obj, prop['attr'], value)
                return True
        except:
            return False
        return False 
Example 2
Project: KStock   Author: aseylys   File: ComboBoxDelegateQt.py    License: GNU General Public License v3.0 6 votes vote down vote up
def displayText(self, value, locale):
        ''' 
        Show str rep of current choice (or choice key if choice is a (key, value) tuple).
        '''
        try:
            if type(value) == QVariant:
                value = value.toPyObject()  # QVariant ==> object
            for choice in self.choices:
                if (type(choice) is tuple) and (len(choice) == 2):
                    # choice is a (key, value) tuple.
                    # Display the key, not the value.
                    key, val = choice
                    if val == value:
                        return str(key)
                else:
                    # choice is a value.
                    # Display it's str rep.
                    if choice == value:
                        return str(choice)
            # If value is not in our list of choices, show str rep of value.
            return str(value)
        except:
            return "" 
Example 3
Project: dash-masternode-tool   Author: Bertrand256   File: wallet_data_models.py    License: MIT License 6 votes vote down vote up
def data(self, index, role=None):
        if index.isValid():
            data = index.internalPointer()
            col = index.column()
            if data:
                if role in (Qt.DisplayRole, Qt.EditRole):
                    if col == 0:
                        # if isinstance(data, Bip44AccountType):
                        #     return data.get_account_name()
                        # else:
                        #     return f'/{data.address_index}: {data.address}'
                        return data
                    elif col == 1:
                        b = data.balance
                        if b:
                            b = b/1e8
                        return b
                    elif col == 2:
                        b = data.received
                        if b:
                            b = b/1e8
                        return b
        return QVariant() 
Example 4
Project: pychemqt   Author: jjgomera   File: mainWindow.py    License: GNU General Public License v3.0 6 votes vote down vote up
def closeEvent(self, event=None):
        if self.okToContinue():
            for tab in range(self.centralwidget.count()):
                centralwidget = self.centralwidget.widget(tab)
                scene = centralwidget.subWindowList()[0].widget().scene()
                scene.clearSelection()
            settings = QtCore.QSettings()
            if self.filename:
                filename = QtCore.QVariant(self.filename)
            else:
                filename = QtCore.QVariant()
            settings.setValue("LastFile", filename)
            if self.recentFiles:
                recentFiles = QtCore.QVariant(self.recentFiles)
            else:
                recentFiles = QtCore.QVariant()
            settings.setValue("RecentFiles", recentFiles)
            settings.setValue("Geometry", QtCore.QVariant(self.saveGeometry()))
            settings.setValue("MainWindow/State",
                              QtCore.QVariant(self.saveState()))
            self.close()
        else:
            event.ignore() 
Example 5
Project: pychemqt   Author: jjgomera   File: mainWindow.py    License: GNU General Public License v3.0 6 votes vote down vote up
def aboutToShow_MenuRecentFiles(self):
        self.menuRecentFiles.clear()
        recentFiles = []
        for fname in self.recentFiles:
            if fname not in self.filename and QtCore.QFile.exists(fname):
                recentFiles.append(fname)
        if recentFiles:
            self.menuRecentFiles.addSeparator()
            for i, fname in enumerate(recentFiles):
                action = QtWidgets.QAction("&%d %s" % (i + 1, fname), self)
                action.setData(QtCore.QVariant(fname))
                action.triggered.connect(self.loadFile)
                self.menuRecentFiles.addAction(action)
        self.menuRecentFiles.addSeparator()
        self.menuRecentFiles.addAction(
            QtGui.QIcon(IMAGE_PATH + "button/clear.png"),
            QtWidgets.QApplication.translate("pychemqt", "Clear"),
            self.clearRecentFiles)

# File Manipulation 
Example 6
Project: Uranium   Author: Ultimaker   File: DefinitionTreeModel.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def data(self, index, role):
        if not self._container:
            return QVariant()

        if not index.isValid():
            return QVariant()

        if role not in self._role_names:
            return QVariant()

        role_name = self._role_names[role]
        definition = index.internalPointer()

        try:
            data = getattr(definition, role_name.decode())
        except AttributeError:
            data = ""

        return QVariant(str(data)) 
Example 7
Project: vorta   Author: borgbase   File: diff_result.py    License: GNU General Public License v3.0 6 votes vote down vote up
def data(self, index, role):
        if not index.isValid():
            return None

        item = index.internalPointer()

        if role == Qt.ForegroundRole:
            if item.itemData[1] == 'removed':
                return QVariant(QColor(Qt.red))
            elif item.itemData[1] == 'added':
                return QVariant(QColor(Qt.green))
            elif item.itemData[1] == 'modified' or item.itemData[1].startswith('['):
                return QVariant(QColor(Qt.darkYellow))

        if role == Qt.DisplayRole:
            return item.data(index.column())
        else:
            return None 
Example 8
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: code_analyzer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def completerModel(self) -> QVariant:
        return QVariant(
            [
                dict(
                    identifier='.IFJcode17',
                    type=Expression.ExpressionTypes.Header
                )
            ] if '.IFJcode17' not in self.code else [] + [
                dict(
                    identifier=match,
                    type=Expression.ExpressionTypes.Types
                ) for match in sorted(("int", "bool", "float", "string"))
            ] + [
                dict(
                    identifier=func,
                    type=Expression.ExpressionTypes.Instruction
                ) for func in INSTRUCTIONS
            ] + [
                dict(
                    identifier=match,
                    type=Expression.ExpressionTypes.Variable
                ) for match in sorted(set(self.VARIABLE_RE.findall(self._code)))
            ]
        ) 
Example 9
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: diff_code_analyzer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def compare(self, new_code: str) -> QVariant:
        diff_lines = []
        hunk = []

        diff = list(unified_diff(self._code.splitlines(True), new_code.splitlines(True)))[2::]
        temp_code_diff = list(unified_diff(self._temp_code.splitlines(True), new_code.splitlines(True)))[2::]

        for line in diff:
            hunk_info_match = re.match(r'@@ -\d+,?\d* \+\d+,?\d* @@', line)
            if hunk_info_match is not None:
                diff_lines.extend(self._get_modified_lines(hunk))
                hunk = []
            hunk.append(line)

        if hunk:
            diff_lines.extend(self._get_modified_lines(hunk))

        added_lines, removed_lines = self._get_lines_diffs(new_code)

        if added_lines:
            self.addedLines.emit(QVariant(added_lines))
        if removed_lines:
            self.removedLines.emit(QVariant(removed_lines))

        return QVariant(diff_lines) 
Example 10
Project: nanovna-saver   Author: NanoVNA-Saver   File: Widget.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setScale(self, scale):
        self.group_box.setMaximumWidth(int(340 * scale))
        self.label['actualfreq'].setMinimumWidth(int(100 * scale))
        self.label['actualfreq'].setMinimumWidth(int(100 * scale))
        self.label['returnloss'].setMinimumWidth(int(80 * scale))
        if self.coloredText:
            color_string = QtCore.QVariant(self.color)
            color_string.convert(QtCore.QVariant.String)
            self.group_box.setStyleSheet(
                f"QGroupBox {{ color: {color_string.value()}; "
                f"font-size: {self._size_str()}}};"
            )
        else:
            self.group_box.setStyleSheet(
                f"QGroupBox {{ font-size: {self._size_str()}}};"
            ) 
Example 11
Project: nanovna-saver   Author: NanoVNA-Saver   File: Widget.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setColor(self, color):
        if color.isValid():
            self.color = color
            p = self.btnColorPicker.palette()
            p.setColor(QtGui.QPalette.ButtonText, self.color)
            self.btnColorPicker.setPalette(p)
        if self.coloredText:
            color_string = QtCore.QVariant(color)
            color_string.convert(QtCore.QVariant.String)
            self.group_box.setStyleSheet(
                f"QGroupBox {{ color: {color_string.value()}; "
                f"font-size: {self._size_str()}}};"
            )
        else:
            self.group_box.setStyleSheet(
                f"QGroupBox {{ font-size: {self._size_str()}}};"
            ) 
Example 12
Project: WeiboSuperSpider   Author: Python3Spiders   File: ListModel.py    License: Apache License 2.0 6 votes vote down vote up
def data(self, index, role):
        if index.isValid() or (0 <= index.row() < len(self.ListItemData)):
            if role == Qt.DisplayRole:
                return QVariant(self.ListItemData[index.row()]['name'])
            elif role == Qt.DecorationRole:
                return QVariant(QIcon(self.ListItemData[index.row()]['iconPath']))
            elif role == Qt.SizeHintRole:
                return QVariant(QSize(70,80))
            elif role == Qt.TextAlignmentRole:
                return QVariant(int(Qt.AlignHCenter|Qt.AlignVCenter))
            elif role == Qt.FontRole:
                font = QFont()
                font.setPixelSize(20)
                return QVariant(font)
        else:            
            return QVariant() 
Example 13
Project: python101   Author: koduj-z-klasa   File: tabmodel_z5.py    License: MIT License 6 votes vote down vote up
def data(self, index, rola=Qt.DisplayRole):
        """ Wyświetlanie danych """
        i = index.row()
        j = index.column()

        if rola == Qt.DisplayRole:
            return '{0}'.format(self.tabela[i][j])
        elif rola == Qt.CheckStateRole and (j == 3 or j == 4):
            if self.tabela[i][j]:
                return Qt.Checked
            else:
                return Qt.Unchecked
        elif rola == Qt.EditRole and j == 1:
            return self.tabela[i][j]
        else:
            return QVariant() 
Example 14
Project: python101   Author: koduj-z-klasa   File: tabmodel_z6.py    License: MIT License 6 votes vote down vote up
def data(self, index, rola=Qt.DisplayRole):
        """ Wyświetlanie danych """
        i = index.row()
        j = index.column()

        if rola == Qt.DisplayRole:
            return '{0}'.format(self.tabela[i][j])
        elif rola == Qt.CheckStateRole and (j == 3 or j == 4):
            if self.tabela[i][j]:
                return Qt.Checked
            else:
                return Qt.Unchecked
        elif rola == Qt.EditRole and j == 1:
            return self.tabela[i][j]
        else:
            return QVariant() 
Example 15
def data(self, index, role=None):
        value = self._anchor_positions[index.row()][index.column()]
        if index.isValid():
            if index.column() == 0:
                if role == Qt.CheckStateRole:
                    return QVariant(value)
            elif index.column() == 1:
                if role == Qt.DisplayRole:
                    return QVariant(value)
            else:
                if role == Qt.DisplayRole:
                    return QVariant('%.2f' % (value))
                elif role == Qt.EditRole:
                    return QVariant(value)
                elif role == Qt.BackgroundRole:
                    return self._get_background(index.row(), index.column())

        return QVariant() 
Example 16
Project: kw_condition   Author: coreanq   File: pandasmodel.py    License: MIT License 5 votes vote down vote up
def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if(role==QtCore.Qt.DisplayRole):
                return self._data.values[index.row()][index.column()]
            else:
                # self._roleName 은 QHash(int, QByteArray)
                columnName = self._roleNames[role].data().decode('utf8')
                print('row {} col {} role {} columnName {} '.format(index.row(), index.column(), role, columnName))
                print(self._data.at[index.row(), columnName])
                return self._data.at[index.row(), columnName]
        return QVariant() 
Example 17
Project: Lector   Author: BasioMeusPuga   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def data(self, index, role):
        source_index = self.mapToSource(index)
        item = self.sourceModel().item(source_index.row(), 0)

        if role == QtCore.Qt.TextAlignmentRole:
            if index.column() in (3, 4):
                return QtCore.Qt.AlignHCenter

        if role == QtCore.Qt.DecorationRole:
            if index.column() == 5:
                return_pixmap = None

                file_exists = item.data(QtCore.Qt.UserRole + 5)
                position_percent = item.data(QtCore.Qt.UserRole + 7)

                if not file_exists:
                    return pie_chart.pixmapper(
                        -1, None, -1, QtCore.Qt.SizeHintRole + 10)

                if position_percent:
                    return_pixmap = pie_chart.pixmapper(
                        position_percent, self.temp_dir,
                        self.consider_read_at,
                        QtCore.Qt.SizeHintRole + 10)

                return return_pixmap

        elif role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            if index.column() in (0, 5):  # Cover and Status
                return QtCore.QVariant()

            if index.column() == 4:
                last_accessed = item.data(self.role_dictionary[index.column()])
                if last_accessed:
                    right_now = QtCore.QDateTime().currentDateTime()
                    time_diff = last_accessed.msecsTo(right_now)
                    return self.time_convert(time_diff // 1000)

            return item.data(self.role_dictionary[index.column()])
        else:
            return QtCore.QVariant() 
Example 18
Project: Lector   Author: BasioMeusPuga   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def data(self, index, role):
        if (index.column() in (4, 5)
                and (role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole)):

            read_field = self.field_dict[index.column()]
            try:
                return self.tag_data[self.filePath(index)][read_field]
            except KeyError:
                return QtCore.QVariant()

        if role == QtCore.Qt.CheckStateRole and index.column() == 0:
            return self.checkState(index)

        return QtWidgets.QFileSystemModel.data(self, index, role) 
Example 19
Project: dash-masternode-tool   Author: Bertrand256   File: wallet_data_models.py    License: MIT License 5 votes vote down vote up
def data(self, index, role=None):
        if index.isValid():
            col_idx = index.column()
            row_idx = index.row()
            if row_idx < len(self.mn_items):
                if role in (Qt.DisplayRole, Qt.EditRole):
                    col = self.col_by_index(col_idx)
                    if col:
                        field_name = col.name
                        if field_name == 'description':
                            return self.mn_items[row_idx]
        return QVariant() 
Example 20
Project: dash-masternode-tool   Author: Bertrand256   File: ext_item_model.py    License: MIT License 5 votes vote down vote up
def headerData(self, section, orientation, role=None):
        if role != 0:
            return QVariant()
        if orientation == 0x1:
            col = self.col_by_index(section)
            if col:
                return col.caption
            return ''
        else:
            return '' 
Example 21
Project: CQ-editor   Author: CadQuery   File: debugger.py    License: Apache License 2.0 5 votes vote down vote up
def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            i = index.row()
            j = index.column()
            return self.frame[i][j]
        else:
            return QtCore.QVariant() 
Example 22
Project: pychemqt   Author: jjgomera   File: UI_spreadsheet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setModelData(self, editor, model, index):
        if index.column() < 4:
            value = editor.currentText()
        else:
            value = editor.text().upper()

        model.setData(index, QtCore.QVariant(value), QtCore.Qt.DisplayRole) 
Example 23
Project: pychemqt   Author: jjgomera   File: delegate.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setModelData(self, editor, model, index):
        value = editor.isChecked()
        model.setData(index, QtCore.QVariant(value), QtCore.Qt.DisplayRole) 
Example 24
Project: pychemqt   Author: jjgomera   File: delegate.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setModelData(self, editor, model, index):
        value = editor.currentText()
        model.setData(index, QtCore.QVariant(value), QtCore.Qt.DisplayRole) 
Example 25
Project: Uranium   Author: Ultimaker   File: ListModel.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def data(self, index, role):
        """Reimplemented from QAbstractListModel"""

        if not index.isValid():
            return QVariant()
        return self._items[index.row()][self._role_names[role].decode("utf-8")] 
Example 26
Project: Uranium   Author: Ultimaker   File: TestSettingDefinitionsModel.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_dataUnhappy():
    model = createModel("single_setting.def.json")
    # Out of bounds
    assert model.data(model.index(250, 0), model.KeyRole) == QVariant()

    # Invalid index
    assert model.data(QModelIndex(), model.KeyRole) == QVariant()

    # Unknown role
    assert model.data(model.index(0, 0), Qt.UserRole + 100) == QVariant()

    empty_model = SettingDefinitionsModel()
    assert empty_model.data(model.index(0, 0), model.KeyRole) == QVariant() 
Example 27
Project: vorta   Author: borgbase   File: notifications.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _dbus_notify(self, header, msg, level='info'):
        item = "org.freedesktop.Notifications"
        path = "/org/freedesktop/Notifications"
        interface = "org.freedesktop.Notifications"
        app_name = "vorta"
        v = QtCore.QVariant(12321)  # random int to identify all notifications
        if v.convert(QtCore.QVariant.UInt):
            id_replace = v
        icon = ""
        title = header
        text = msg
        actions_list = QtDBus.QDBusArgument([], QtCore.QMetaType.QStringList)
        hint = {'urgency': self.URGENCY[level]}
        time = 5000   # milliseconds for display timeout

        bus = QtDBus.QDBusConnection.sessionBus()
        notify = QtDBus.QDBusInterface(item, path, interface, bus)
        if notify.isValid():
            x = notify.call(QtDBus.QDBus.AutoDetect, "Notify", app_name,
                            id_replace, icon, title, text,
                            actions_list, hint, time)
            if x.errorName():
                logger.warning("Failed to send notification!")
                logger.warning(x.errorMessage())
        else:
            logger.warning("Invalid dbus interface") 
Example 28
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: code_analyzer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def highlightRules(self) -> QVariant:
        return QVariant([dict(pattern=pattern, color=color)
                         for (pattern, color) in HIGHLIGHT_RULES]
                        ) 
Example 29
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: code_analyzer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def expressionSplitters(self) -> QVariant:
        return QVariant(list(EXPRESSION_SPLITTERS)) 
Example 30
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: exp_analyzer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def currentWordBorders(self) -> QVariant:
        return QVariant(self._currentWordBorders())