def dropMimeData(self, data, action, row, column, parent):
        if data.hasFormat("application/target.tableitem.creepy"):
            encodedData = data.data("application/target.tableitem.creepy")
            stream = QDataStream(encodedData, QIODevice.ReadOnly)
            columnsList = []
            qVariant = QVariant()
            while not stream.atEnd():
                stream >> qVariant
                columnsList.append(qVariant.toPyObject())
            draggedRows = [columnsList[x : x + 5] for x in range(0, len(columnsList), 5)]
            droppedRows = []
            for row in draggedRows:
                # Ensure we are not putting duplicates in the target list
                existed = False
                for target in self.targets:
                    if row[2] == target["targetUsername"] and row[0] == target["pluginName"]:
                        existed = True
                if not existed:
                    droppedRows.append(
                        {
                            "targetUsername": row[2],
                            "targetFullname": row[3],
                            "targetPicture": row[1],
                            "targetUserid": row[4],
                            "pluginName": row[0],
                        }
                    )
            self.insertRows(droppedRows, len(droppedRows), parent)

        return True
예제 #2
0
    def _do(self, new, old):
        if new.toString() == '':
            new = QVariant()
        elif new.toString() == '""':
            new = QVariant(QString(''))

        self.model.rows[self.row][self.column] = new

        if self.column == 0:
            # commented or uncommented
            index1 = self.model.index(self.row, 0)
            index2 = self.model.index(self.row, self.model.columnCount()-1)
        elif self.column==1:
            # we have just changed the object name, other objects might
            # reference it
            index1 = self.model.index(0, 0)
            index2 = self.model.index(
                self.model.rowCount()-1, self.model.columnCount()-1)
        else:
            # just changed this cell
            index1 = self.model.index(self.row, self.column)
            index2 = index1
        self.model.emit(
            SIGNAL('dataChanged(const QModelIndex &, const QModelIndex &)'),
            index1, index2)
예제 #3
0
파일: query.py 프로젝트: jsj2008/kdegames
 def __convertField(self, idx):
     """convert a QSqlQuery field into a python value"""
     field = self.fields[idx]
     name = str(field.name())
     valType = field.type()
     if valType == QVariant.String:
         value = unicode(self.query.value(idx).toString())
     elif valType == QVariant.Double:
         value = self.query.value(idx).toDouble()[0]
     elif valType == QVariant.Int:
         value = unicode(self.query.value(idx).toString())
         if '.' in value:
             # rule.limits is defined as integer in older versions
             # but we save floats anyway. Sqlite3 lets us do a lot
             # of illegal things...
             value = self.query.value(idx).toDouble()[0]
         else:
             value = self.query.value(idx).toInt()[0]
     elif valType == QVariant.UInt:
         value = self.query.value(idx).toUInt()[0]
     elif valType == QVariant.LongLong:
         value = self.query.value(idx).toLongLong()[0]
     elif valType == QVariant.ULongLong:
         value = self.query.value(idx).toULongLong()[0]
     elif valType == QVariant.Invalid:
         value = None
     else:
         raise Exception('Query: variant type %s not implemented for field %s ' % \
             (QVariant.typeToName(valType), name))
     return value
예제 #4
0
 def loadResource(self, type, name):
     ret = QVariant()
     name.setFragment(QString())
     if type == QTextDocument.HtmlResource:
         loop = QEventLoop()
         self.connect(self.http, SIGNAL("done(bool)"), loop, SLOT("quit()"))
         self.http.get(name.toString())
         loop.exec_(QEventLoop.AllEvents|QEventLoop.WaitForMoreEvents)
         data = QVariant(QString(self.html))
         if data.toString().trimmed().isEmpty():
             fileName = QFileInfo(
             name.toLocalFile()).fileName()
             data = QTextBrowser.loadResource(self, type, QUrl(fileName))
     else:
         fileName = QFileInfo(
         name.toLocalFile()).fileName()
         data = QTextBrowser.loadResource(self, type, QUrl(fileName))
     return data
예제 #5
0
    def setData(self, index, value, role):
        ''' PyQt API Method -- See the PyQt documentation for a description '''
        if not index.isValid():
            return False

        item = index.internalPointer()
        node = item.node

        is_checkbox_node = node.tag == 'selectable' or node.get('type') == 'boolean'

        # only allow editing in second column
        if index.column() != 1:
            return False

        # user clicking on a checkbox
        if role == Qt.CheckStateRole and is_checkbox_node:
            # ask the users if they want to make inherited nodes local first
            if node.get('inherited'):
                title = 'Editing inherited node'
                msg = ("'%s' is inherited from a parent project. \n\n"
                       "Do you want to make this node part of this project "
                       "so that you can edit it?" % node.get('name') or node.tag)
                b = (QMessageBox.Yes, QMessageBox.No)
                ans = QMessageBox.question(None, title, msg, *b)
                if ans == QMessageBox.Yes:
                    self.make_item_local(item)
                else:
                    return False
                del title, msg, b, ans # Clean up namespace
            if value.toInt()[0] == Qt.Checked:
                value = QVariant('True')
            else:
                value = QVariant('False')

        # convert the value to a string and set the nodes text value
        value = value.toString()
        changed_value = node.text != value
        if changed_value:
            node.text = str(value) # avoid QString's in the xml
            self.dirty = True
            s = SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)")
            self.emit(s, index, index)
        return True
예제 #6
0
    def _updateRecentFileActions(self):
        files = list(self.settings.value("recentFileList").toStringList())
        fileNames = {}
        numRecentFiles = min(len(files), self.MaxRecentFiles)

        for action in self.recentFileActions:
            action.setVisible(False)
            
        for i in range(numRecentFiles):
            fileName = QFileInfo(files[i]).fileName()
            if fileName in fileNames.keys():
                fileNames[fileName] += 1
            else:
                fileNames[fileName] = 1

        for i in range(numRecentFiles):
            fileName = QFileInfo(files[i]).fileName()
            filePath = QVariant(files[i])
            action = self.recentFileActions[i]
            action.setText(fileNames[fileName] == 1 and fileName or filePath.toString())
            action.setData(filePath)
            action.setVisible(True)
        self.emit(SIGNAL("recentFileActionsAvailable(bool)"), numRecentFiles > 0)
예제 #7
0
파일: tools.py 프로젝트: maximerobin/Ufwi
def CreateQVariantList(items):
    """Check that all items are QVariant
       and return QVariant object that contains items
    """
    for item in items:
        if not isinstance(item, QVariant):
            raise NotImplementedError("'%s' must be wrapped in 'QVariant'"
                % type(item))

    if hasattr(QVariant, "fromList"):
        # With PyQt >= 4.4.3, QVariant(list of QVariant) behaviour changed:
        # QVariant.fromList() should be used instead to get the same behaviour
        # than QVariant(list of QVariant) with PyQt 4.4.2.
        return QVariant.fromList(items)
    else:
        # PyQt <= 4.4.2
        return QVariant(items)
예제 #8
0
    def editorEvent(self, event, model, option, index):
        #print "editor event"
        if event.type() == QEvent.MouseButtonDblClick and model.isList(index):
            # read-only ?
            if model.flags(index) & Qt.ItemIsEditable: mode = 'w'
            else: mode = 'r'
            #print mode
            data = model.data(index, role=Qt.EditRole)
            fm = SimpleListDlg(datalist=data, mode = mode)
            fm.setModal(True)
            fm.exec_()
            if fm.values:
                #print fm.values
                vals = QVariant.fromList([QVariant(d) for d in fm.values])
                model.setData(index, vals)
            return True

        return QStyledItemDelegate.editorEvent(self, event, model, option, index)
예제 #9
0
    def writeAttributeRow(self, rowNr, attributes):
        colNr = 0
        for cell in attributes:
            # QGIS2.0 does not have QVariants anymore, only for <2.0:
            if QGis.QGIS_VERSION_INT < 10900:
                cell = QVariant(cell)
                if cell.canConvert(QVariant.Int) and cell.toInt()[1]:
                    cell = cell.toInt()[0]
                elif cell.canConvert(QVariant.Double) and cell.toDouble()[1]:
                    cell = cell.toDouble()[0]
                else:
                    cell = unicode(cell.toString())
            # handle NULL values by writing 'NULL'
            if not cell:
                cell = ''
            else:
                cell = unicode(cell)
                try:
                    cell = float(cell)
                except:
                    pass

            self.ws.write(rowNr, colNr, cell)
            colNr = colNr + 1
예제 #10
0
파일: popgrid.py 프로젝트: gem/sidd
    def do_operation(self):
        """ perform footprint load operation """

        # input/output data checking already done during property set
        # load and verify
        popgrid_file = self.inputs[0].value
        pop_field = self.inputs[1].value

        popgrid_layername = 'zone_%s' % get_unique_filename()
        try:
            tmp_popgrid_layer = load_shapefile_verify(popgrid_file,
                                                      popgrid_layername,
                                                      [pop_field])
        except AssertionError as err:
            raise OperatorError(str(err), self.__class__)

        logAPICall.log(
            'tmp_fp_layer.crs().epsg() %s ' % tmp_popgrid_layer.crs().epsg(),
            logAPICall.DEBUG)
        if tmp_popgrid_layer.crs().epsg() != self._crs.epsg():
            transform = QgsCoordinateTransform(tmp_popgrid_layer.crs(),
                                               self._crs)
            transform_required = True
        else:
            transform_required = False

        # output grid
        fields = {
            0: QgsField(GID_FIELD_NAME, QVariant.Int),
            1: QgsField(CNT_FIELD_NAME, QVariant.Double),
        }
        pop_idx = layer_field_index(tmp_popgrid_layer, pop_field)
        output_file = '%spop_grid_%s.shp' % (self._tmp_dir,
                                             get_unique_filename())
        logAPICall.log('create outputfile %s ... ' % output_file,
                       logAPICall.DEBUG)
        try:
            writer = QgsVectorFileWriter(output_file, "utf-8", fields,
                                         QGis.WKBPoint, self._crs,
                                         "ESRI Shapefile")
            f = QgsFeature()
            gid = 0
            for _f in layer_features(tmp_popgrid_layer):
                # NOTE: geom.transform does projection in place to underlying C object

                # 1. get geometry
                geom = _f.geometry()
                # 2. change project if required
                if transform_required:
                    geom = transform.transform(geom)

                # 3. write to file
                gid += 1
                f.setGeometry(geom)
                f.addAttribute(0, QVariant(gid))
                f.addAttribute(1, _f.attributeMap()[pop_idx])
                writer.addFeature(f)
            del writer, f
        except Exception as err:
            remove_shapefile(output_file)
            raise OperatorError("error creating footprint centroids: %s" % err,
                                self.__class__)

        popgrid_layername = 'popgrid_%s' % get_unique_filename()
        popgrid_layer = load_shapefile(output_file, popgrid_layername)
        if not popgrid_layer:
            raise OperatorError(
                'Error loading footprint centroid file' % (output_file),
                self.__class__)

        # clean up
        del tmp_popgrid_layer

        # store data in output
        self.outputs[0].value = popgrid_layer
        self.outputs[1].value = output_file
예제 #11
0
    def data(self, idx, role=Qt.DisplayRole):

        e = self.get(idx.row())
        col = idx.column()
        if role != Qt.DisplayRole:
            return QVariant()
        if col == COL_ESDC:
            return QVariant(e.esdc_str)
        elif col == COL_TEXT:
            return QVariant(e.text)
        elif col == COL_ALL_GROUNDINGS:
            return QVariant(e.all_groundings_str)
        elif col == COL_GROUNDINGS:
            return QVariant(e.groundings_str)
        elif col == COL_PROBABILITY:
            #return QVariant("%e" % e.probability)
            return QVariant("%.60f" % e.probability)
        elif col == COL_COST:
            return QVariant("%e" % e.cost)
        elif col == COL_RECOMPUTED_PROBABILITY:
            return QVariant("%e" % e.recomputed_prob)
        elif col == COL_RECOMPUTED_COST:
            return QVariant("%e" % e.recomputed_cost)
        elif col == COL_OVERALL_COST:
            return QVariant("%e" % e.overall_cost)
        elif col == COL_OVERALL_PROB:
            return QVariant("%e" % e.overall_prob)
        elif col == COL_PHI_VALUE:
            return QVariant(str(e.phi_value))
        else:
            raise ValueError("Bad id: %s" % col)
예제 #12
0
 def __init__(self):
     super(Cell, self).__init__()
     self.value = QVariant()
     self.cacheIsDirty=False
     self.cachedValue =  QVariant()
     self.setDirty()
예제 #13
0
def makeUrlItem(v):
    item = QStandardItem(v)
    item.setData(QVariant(v), DataRoles.url)
    item.setData(QVariant(''), DataRoles.urlTitle)
    return item
예제 #14
0
 def headerData(self, col, orientation, role):
     if orientation == Qt.Horizontal and role == Qt.DisplayRole:
         return QVariant(self.fields[col][0])
     return QVariant()
예제 #15
0
class Cell(QObject):
    def __init__(self):
        super(Cell, self).__init__()
        self.value = QVariant()
        self.cacheIsDirty = False
        self.cachedValue = QVariant()
        self.setDirty()

    def clone(self):
        return deepcopy(self)

    def setData(self, role, value):
        QTableWidgetItem.setData(role, value)
        if (role == Qt.EditRole):
            self.setDirty()

    def data(self, role):
        if role == Qt.DisplayRole:
            if self.value.isValid():
                return self.value.toString()
            else:
                return "####"

        elif (role == Qt.TextAlignmentRole):
            if (self.value.type() == QVariant.String):
                return int(Qt.AlignLeft | Qt.AlignVCenter)
            else:
                return int(Qt.AlignRight | Qt.AlignVCenter)
        else:
            return QTableWidgetItem.data(role)

    # def setFormula(self, &formula):
    def setFormula(self, formula):
        self.setData(Qt.EditRole, formula)

    def formula(self):
        return self.data(Qt.EditRole).toString()

    def setDirty(self):
        self.cacheIsDirty = True

    def value(self):

        if (self.cacheIsDirty):
            self.cacheIsDirty = False

            formulaStr = self.formula()
            if (formulaStr.startsWith('\'')):
                self.cachedValue = formulaStr.mid(1)
            elif (formulaStr.startsWith('=')):
                self.cachedValue = self.Invalid
                expr = QString(formulaStr.mid(1))
                expr.replace(" ", "")
                expr.append(QChar.Null)

                pos = int(0)
                cachedValue = self.evalExpression(expr, pos)
                if (expr[pos] != QChar.Null):
                    cachedValue = self.Invalid
            else:
                pass
                ok = bool(False)
                # double d = formulaStr.toDouble(&ok)
                # if (ok)
                #     cachedValue = d
                #  else
                #     cachedValue = formulaStr
                #

        return self.cachedValue

    # def evalExpression(const QString &str, int &pos) const
    def evalExpression(self, str, pos):

        result = QVariant(self.evalTerm(str, pos))
        # while (str[pos] != QChar.Null):
        #     op = QChar(str[pos])
        #     if (op != '+' && op != '-'):
        #         return result
        #     pos = pos + 1
        #
        #     term = QVariant(self.evalTerm(str, pos))
        #     if (result.type() == QVariant.Double
        #             && term.type() == QVariant.Double)
        #         if (op == '+')
        #             result = result.toDouble() + term.toDouble()
        #          else
        #             result = result.toDouble() - term.toDouble()
        #
        #      else
        #         result = Invalid

        return QVariant(result)

    # QVariant Cell.evalTerm(const QString &str, int &pos) const
    def evalTerm(self, str, pos):
        pass
        #
        # QVariant result = evalFactor(str, pos)
        # while (str[pos] != QChar.Null)
        #     QChar op = str[pos]
        #     if (op != '*' && op != '/')
        #         return result
        #     ++pos
        #
        #     QVariant factor = evalFactor(str, pos)
        #     if (result.type() == QVariant.Double
        #             && factor.type() == QVariant.Double)
        #         if (op == '*')
        #             result = result.toDouble() * factor.toDouble()
        #          else
        #             if (factor.toDouble() == 0.0)
        #                 result = Invalid
        #              else
        #                 result = result.toDouble() / factor.toDouble()
        #
        #
        #      else
        #         result = Invalid
        #

        # return result
        return QVariant(0)

    # QVariant Cell.evalFactor(const QString &str, int &pos) const
    def evalFactor(self, str, pos):
        #
        # QVariant result
        # bool negative = false
        #
        # if (str[pos] == '-')
        #     negative = true
        #     ++pos
        #
        #
        # if (str[pos] == '(')
        #     ++pos
        #     result = evalExpression(str, pos)
        #     if (str[pos] != ')')
        #         result = Invalid
        #     ++pos
        #  else
        #     QRegExp regExp("[A-Za-z][1-9][0-9]0,2")
        #     QString token
        #
        #     while (str[pos].isLetterOrNumber() || str[pos] == '.')
        #         token += str[pos]
        #         ++pos
        #
        #
        #     if (regExp.exactMatch(token))
        #         int column = token[0].toUpper().unicode() - 'A'
        #         int row = token.mid(1).toInt() - 1
        #
        #         Cell *c = static_cast<Cell *>(
        #                           tableWidget()->item(row, column))
        #         if (c)
        #             result = c->value()
        #          else
        #             result = 0.0
        #
        #      else
        #         bool ok
        #         result = token.toDouble(&ok)
        #         if (!ok)
        #             result = Invalid
        #
        #
        #
        # if (negative)
        #     if (result.type() == QVariant.Double)
        #         result = -result.toDouble()
        #      else
        #         result = Invalid
        #
        #
        # return result

        return QVariant(0)
예제 #16
0
 def data(self, index, role):
     if not index.isValid():
         return QVariant()
     elif role != Qt.DisplayRole:
         return QVariant()
     return QVariant(self.arraydata[index.row()][index.column()])
예제 #17
0
 def headerData(self, col, orientation, role=QtCore.Qt.DisplayRole):
     if (role == QtCore.Qt.DisplayRole
             and orientation == QtCore.Qt.Horizontal):
         return QVariant(self.headers[col])
     return QAbstractTableModel.headerData(self, col, orientation, role)
예제 #18
0
 def _display_data(self, index):
     """Return a data element"""
     return QVariant(self._data[index.row()][index.column()])
예제 #19
0
파일: tree.py 프로젝트: kzwkt/dff
  def data(self, index, role):
    """
    \reimp

    Nodes' pointers are encapsulated in QStandardItem (role : Qt.UserRole + 1). Most
    of the data can only be retrieved only if the node is retrieved:

    * The node name
    * The node icon
    * ...

    To do so, the TreeModel.data() method calls the QStandardItemModel.data() method by passing
    the `index` parameter and `Qt.UserRole + 1` or `Qt.UserRole + 2` to it. In the second case, it
    retrieves a boolean used to know if the node is already expended and returns directly.

    \param index the index of the data we want to get
    \param role the role of the data we want to retrieve

    \return a QVariant containing the data, or an invalid QVariant if the data could not be retrieved.
    """
    if not index.isValid():
      return QVariant()
    # Qt.UserRole + 2 contain a boolean indicating if the node has already been expanded
    # in the tree.
    if role == Qt.UserRole + 3:
      return QStandardItemModel.data(self, index, role)
    if role == Qt.UserRole + 2:
      return QStandardItemModel.data(self, index, role)
    # call QStandardItemModel.data method with a Qt.UserRole + 1 to get the pointer on the node
    # (returns a invalid QVariant if the node or the data is None)
    data = QStandardItemModel.data(self, index, Qt.UserRole + 1)
    if not data.isValid():
      return data
    # getting the node or returning an invalid QVariant() if the node is not valid
    node = self.VFS.getNodeFromPointer(data.toULongLong()[0])
    if node == None:
      return QVariant()
    # if role == UserRole + 1, it means that the node itself must be returned (the pointer
    # on the node, encapsulated in a QVariant()
    if role == (Qt.UserRole + 1):
      return data
    # in other cases, returns the requires data  : icon, color, etc. or an invalid QVariant()
    # if the role does not correpond to anything.
    if role == Qt.DisplayRole :
      return QVariant(QString.fromUtf8(node.name()))
    if role == Qt.DecorationRole:
      pixmap = QPixmap(node.icon())
      if node.hasChildren():
        try:
          pfsobj = node.children()[0].fsobj().this
        except AttributeError:
  	  pfsobj = None
        try:
          nfsobj = node.fsobj().this
        except AttributeError:
	  nfsobj = None
        if pfsobj != nfsobj:
          pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio)
          painter = QPainter(pixmap)
          rootPixmap = QPixmap(":root")
          painter.drawPixmap(0, 0, rootPixmap)
          painter.end()
      return QVariant(QIcon(pixmap))

    if role == Qt.BackgroundRole:
      if index == self.currentIndex:
        palette = QPalette().color(QPalette.Highlight)
        return QVariant(QColor(palette))
    if role == Qt.ForegroundRole:
      if (index == self.currentIndex) and not node.isDeleted():
        palette = QPalette().color(QPalette.HighlightedText)
        return QVariant(QColor(palette))
      if node.isDeleted():
        return  QVariant(QColor(Qt.red))
    if self.ch == True:
      if role == Qt.CheckStateRole:
        if index.column() == 0:
          if long(node.this) in self.selection.get():
            return Qt.Checked
          else:
            return Qt.Unchecked

    return QVariant()
예제 #20
0
 def value(self, name, default=None):
     try:
         return QVariant(self.config[self.currentgroup][name])
     except KeyError:
         return QVariant(default)
예제 #21
0
 def clearRecentDocuments(self):
     self.settings.setValue("recentFileList", QVariant(QStringList()))
     self._updateRecentFileActions()
예제 #22
0
 def _set_lastDir(self, lastDir):
     self._lastDir = lastDir
     self.settings.setValue("lastDir", QVariant(lastDir))
예제 #23
0
파일: ksmarttray.py 프로젝트: leemgs/smart
for author in AUTHORS:
    name, email = author.rsplit(" ", 1)
    aboutData.addAuthor(ki18n(name), ki18n(""), email.strip("<>"), "")

KCmdLineArgs.init(sys.argv, aboutData)
app = KApplication()

import smart
ctrl = smart.init()

mainWindow = KMainWindow()
smart_icon = QIcon(getPixmap("smart"))
mainWindow.setWindowIcon(smart_icon)
sysTray = QSystemTrayIcon(smart_icon, None)
smart_image = getPixmap("smart").toImage()
aboutData.setProgramLogo(QVariant(smart_image))

menu = QMenu(None)
menu.addAction(KIcon("view-refresh"), "Check for updates", smart_update)
menu.addAction(smart_icon, "Launch Smart", smart_gui)
menu.addSeparator()
menu.addAction(KIcon("help-about"), "About", show_about)
menu.addAction(KIcon("application-exit"), "Quit", exit_applet)
sysTray.setContextMenu(menu)

sysTray.show()

app.exec_()

# vim:ts=4:sw=4:et
예제 #24
0
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.__root.name()

        return QVariant()
예제 #25
0
파일: models.py 프로젝트: octogene/kcnrtl
 def data(self, index, role):
     if index.isValid() and role == Qt.DisplayRole:
         return QVariant(self.listdata[index.row()])
     else:
         return QVariant()
예제 #26
0
    def __init__(self, parent=None):
        super(ContactDlg, self).__init__(parent)

        forenameLabel = QLabel("&Forename:")
        self.forenameEdit = QLineEdit()
        forenameLabel.setBuddy(self.forenameEdit)
        surnameLabel = QLabel("&Surname:")
        self.surnameEdit = QLineEdit()
        surnameLabel.setBuddy(self.surnameEdit)
        categoryLabel = QLabel("&Category:")
        self.categoryComboBox = QComboBox()
        categoryLabel.setBuddy(self.categoryComboBox)
        self.categoryComboBox.addItems(["Business", "Domestic", "Personal"])
        companyLabel = QLabel("C&ompany:")
        self.companyEdit = QLineEdit()
        companyLabel.setBuddy(self.companyEdit)
        addressLabel = QLabel("A&ddress:")
        self.addressEdit = QLineEdit()
        addressLabel.setBuddy(self.addressEdit)
        phoneLabel = QLabel("&Phone:")
        self.phoneEdit = QLineEdit()
        phoneLabel.setBuddy(self.phoneEdit)
        mobileLabel = QLabel("&Mobile:")
        self.mobileEdit = QLineEdit()
        mobileLabel.setBuddy(self.mobileEdit)
        faxLabel = QLabel("Fa&x:")
        self.faxEdit = QLineEdit()
        faxLabel.setBuddy(self.faxEdit)
        emailLabel = QLabel("&Email:")
        self.emailEdit = QLineEdit()
        emailLabel.setBuddy(self.emailEdit)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        addButton = self.buttonBox.button(QDialogButtonBox.Ok)
        addButton.setText("&Add")
        addButton.setEnabled(False)

        grid = QGridLayout()
        grid.addWidget(forenameLabel, 0, 0)
        grid.addWidget(self.forenameEdit, 0, 1)
        grid.addWidget(surnameLabel, 0, 2)
        grid.addWidget(self.surnameEdit, 0, 3)
        grid.addWidget(categoryLabel, 1, 0)
        grid.addWidget(self.categoryComboBox, 1, 1)
        grid.addWidget(companyLabel, 1, 2)
        grid.addWidget(self.companyEdit, 1, 3)
        grid.addWidget(addressLabel, 2, 0)
        grid.addWidget(self.addressEdit, 2, 1, 1, 3)
        grid.addWidget(phoneLabel, 3, 0)
        grid.addWidget(self.phoneEdit, 3, 1)
        grid.addWidget(mobileLabel, 3, 2)
        grid.addWidget(self.mobileEdit, 3, 3)
        grid.addWidget(faxLabel, 4, 0)
        grid.addWidget(self.faxEdit, 4, 1)
        grid.addWidget(emailLabel, 4, 2)
        grid.addWidget(self.emailEdit, 4, 3)
        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

        self.lineedits = (self.forenameEdit, self.surnameEdit,
                          self.companyEdit, self.phoneEdit, self.emailEdit)
        for lineEdit in self.lineedits:
            lineEdit.setProperty("mandatory", QVariant(True))
            self.connect(lineEdit, SIGNAL("textEdited(QString)"),
                         self.updateUi)
        self.connect(self.categoryComboBox, SIGNAL("activated(int)"),
                     self.updateUi)

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

        self.setStyleSheet(ContactDlg.StyleSheet)
        self.setWindowTitle("Add Contact")
예제 #27
0
 def getBackgroundColor(self, values):
     val = values[0]
     colorName = forceString(val)
     if colorName:
         return QVariant(QtGui.QColor(colorName))
     return CCol.invalid
예제 #28
0
 def __init__(self):
     super(Cell, self).__init__()
     self.value = QVariant()
     self.cacheIsDirty = False
     self.cachedValue = QVariant()
     self.setDirty()
예제 #29
0
 def headerData(self, section, orientation, role):
     if (orientation == Qt.Horizontal and role == Qt.DisplayRole):
         assert 0 <= section <= len(self.headers)
         return QVariant(self.headers[section])
     return QVariant()
예제 #30
0
def makeUrlAction(text, url, toolTip='', parent=None):
    action = QAction(text + '...', parent)
    action.setData(QVariant(url))
    action.setToolTip(toolTip)
    return action
예제 #31
0
class GraphicsWidget(RWidget):         

    def __init__(self, parent):
        RWidget.__init__(self, parent)
        self.parent = parent
        self._hist = History(items=[])
        self._currentPlot = QVariant(QString())
        
        self.callLineEdit = QLineEdit()
        self.callLineEdit.setReadOnly(True)
        self.callLineEdit.setToolTip("Commands to reproduce plot")
        self.callLineEdit.setWhatsThis("Commands to reproduce plot")
        actions = []

#        playAction = QAction("Replay", self)
#        playAction.setStatusTip("Replay selected plot")
#        playAction.setToolTip("Replay selected plot")
#        playAction.setIcon(QIcon(":edit-copy"))
#        actions.append(playAction)
        
        firstAction = QAction("End", self)
        firstAction.setStatusTip("Move to end of history")
        firstAction.setToolTip("Move to end of history")
        firstAction.setIcon(QIcon(":go-first"))
        actions.append(firstAction)
        
        previousAction = QAction("Previous", self)
        previousAction.setStatusTip("Move to previous plot")
        previousAction.setToolTip("Move to previous plot")
        previousAction.setIcon(QIcon(":go-previous"))
        actions.append(previousAction)

        infoAction = QAction("Info", self)
        infoAction.setStatusTip("Show plot info")
        infoAction.setToolTip("Show plot info")
        infoAction.setIcon(QIcon(":gtk-info"))
        actions.append(infoAction)
        
        nextAction = QAction("Next", self)
        nextAction.setStatusTip("Move to next plot")
        nextAction.setToolTip("Move to next plot")
        nextAction.setIcon(QIcon(":go-next"))
        actions.append(nextAction)
        
        lastAction = QAction("Start", self)
        lastAction.setStatusTip("Move to latest plot")
        lastAction.setToolTip("Move to latest plot")
        lastAction.setIcon(QIcon(":go-last"))
        actions.append(lastAction)
        actions.append(None)
        
        clearAction = QAction("Clear", self)
        clearAction.setStatusTip("Clear plot history")
        clearAction.setToolTip("Clear plot history")
        clearAction.setIcon(QIcon(":edit-clear"))
        actions.append(clearAction)
        

        hbox = QHBoxLayout()
        for action in actions:
            if not action is None:
                button = QToolButton()
                button.setDefaultAction(action)
                button.setAutoRaise(True)
                hbox.addWidget(button)
            else:
                hbox.addWidget(self.callLineEdit)
        self.setLayout(hbox)

        self.connect(firstAction, SIGNAL("triggered()"), self.first)
        self.connect(previousAction, SIGNAL("triggered()"), self.previous)
        self.connect(infoAction, SIGNAL("triggered()"), self.info)
        self.connect(nextAction, SIGNAL("triggered()"), self.next)
        self.connect(lastAction, SIGNAL("triggered()"), self.last)
        self.connect(clearAction, SIGNAL("triggered()"), self.clear)
        
    def setHistory(self, history):
        self._hist = history

    def history(self):
        return self._hist

    def previous(self):
        return self.navigateHistory(True)

    def next(self):
        return self.navigateHistory(False)

    def navigateHistory(self, up=True):
        if up:
            self._currentPlot = self.history().previous()
        else:
            self._currentPlot = self.history().next()
        tmp = self._currentPlot.toPyObject()
        if not tmp == QString():
            self.callLineEdit.setText(tmp[2])
        return self._currentPlot

    def first(self):
        temp = self.previous()
        item = self._currentPlot
        while not isinstance(temp,QVariant):
            item = temp
            temp = self.previous()
        self._currentPlot = item

    def last(self):
        temp = self.next()
        item = self._currentPlot
        while not isinstance(temp,QVariant):
            item = temp
            temp = self.next()
        self._currentPlot = item          

    def info(self):
        plot = self._currentPlot.toPyObject()
        if isinstance(plot,QString):
            return
        plot = self._currentPlot.toPyObject()
        msgBox = QMessageBox()
        msgBox.setText("Plot information:")
        msgBox.setInformativeText("Original device: %s" % str(plot[0])
                                  +"\nHistory position: %s" % str(self.history().currentIndex()+1)
                                  +"\nSize: %s bytes" % str(plot[1])
                                  +"\n\nWould you like to replay the plot now?")
        msgBox.setDetailedText("Original call:\n%s" % plot[2])
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Close)
        msgBox.setDefaultButton(QMessageBox.Ok)
        if msgBox.exec_() == QMessageBox.Ok:
            print plot[3]

    def clear(self):
        self.setHistory(History(items=[]))
        self.callLineEdit.setText(QString())
        
    def updateHistory(self, item):
        self.history().update([item])
        self.previous()        
예제 #32
0
 def setModelData(self, editor, model, index):
     model.setData(index, QVariant(editor.text()))
예제 #33
0
 def data(self, index, role):
     col = index.column()
     row = index.row()
     value = self.rows[row][col]
     # default view
     if role == Qt.DisplayRole:
         # comment row
         if col == 1:
             if len(value.toString()) > 0:
                 return QVariant("#..")
             else:
                 return QVariant()
         # if the cell is defaulted, display the default value
         elif self._isDefault(value, col):
             value = self._defaults[col]
         # if we've got a combo box lookup the appropriate value for the enum
         if col in self._cValues:
             # lookup the display in the list of _cItems
             for i, v in enumerate(self._cValues[col]):
                 if v.toString() == value.toString():
                     return QVariant(self._cItems[col].toStringList()[i])
         # display commented out rows as X
         elif col == 0:
             if value.toBool():
                 return QVariant(QString('X'))
             else:
                 return QVariant(QString(''))
         # empty string rows should be ""
         elif not value.isNull() and self._types[col] == str and \
                 str(value.toString()) == '' and col != 1:
             value = QVariant(QString('""'))
         return value
     # text editor
     elif role == Qt.EditRole:
         # if the cell is defaulted, display the default value
         if self._isDefault(value, col):
             value = self._defaults[col]
         # if we've got a combo box lookup the appropriate value for the enum
         if col in self._cValues:
             # lookup the display in the list of _cItems
             for i, v in enumerate(self._cValues[col]):
                 if v.toString() == value.toString():
                     return QVariant(self._cItems[col].toStringList()[i])
         # empty string rows should be ""
         elif not value.isNull() and self._types[col] == str and \
                 str(value.toString()) == '' and col != 1:
             value = QVariant(QString('""'))
         return value
     elif role == Qt.ToolTipRole:
         # tooltip
         error = self._isInvalid(value, row, col)
         text = str(self._tooltips[col].toString())
         if error:
             text = '***Error: %s\n%s'%(error, text)
         if col in self._idents:
             lines = ['\nPossible Values: ']
             for name in self._nameList(filt = self._types[col], upto = row):
                 if len(lines[-1]) > 80:
                     lines.append('')
                 lines[-1] += str(name) + ', '
             text += '\n'.join(lines).rstrip(' ,')
         if col == 1 and len(value.toString()) > 0:
             text += ":\n\n" + value.toString()
         return QVariant(text)
     elif role == Qt.ForegroundRole:
         # cell foreground
         if self._isCommented(row):
             # comment
             return QVariant(QColor(120,140,180))
         if self._isDefault(value, col):
             # is default arg (always valid)
             return QVariant(QColor(160,160,160))
         elif self._isInvalid(value, row, col):
             # invalid
             return QVariant(QColor(255,0,0))
         else:
             # valid
             return QVariant(QColor(0,0,0))
     elif role == Qt.BackgroundRole:
         # cell background
         if self._isCommented(row):
             # commented
             return QVariant(QColor(160,180,220))
         elif self._isInvalid(value, row, col):
             # invalid
             return QVariant(QColor(255,200,200))
         elif col in self._defaults:
             # has default
             return QVariant(QColor(255,255,240))
         elif col in self._optional:
             #is optional
             return QVariant(QColor(180,180,180))
         else:
             # valid
             return QVariant(QColor(250,250,250))
     elif role == Qt.UserRole:
         # combo box asking for list of items
         if col in self._idents:
             return QVariant(
                 self._nameList(filt = self._types[col], upto = row))
         elif col in self._cItems:
             return self._cItems[col]
         else:
             return QVariant()
     else:
         return QVariant()
예제 #34
0
파일: float.py 프로젝트: khedron/Plot
	def _variant_to_scalar(data):
		result, valid = QVariant.toDouble(data)
		if not valid:
			raise TypeError, "float_type.variant_to_scalar: QVariant expected"
		else:
			return result
예제 #35
0
 def setModelData(self, editor, model, index):
     editor.interpretText()
     model.setData(index, QVariant(editor.value()))
예제 #36
0
class Cell(QObject):
    def __init__(self):
        super(Cell, self).__init__()
        self.value = QVariant()
        self.cacheIsDirty=False
        self.cachedValue =  QVariant()
        self.setDirty()
    def clone(self):
       return deepcopy(self)

    def setData(self,role,value):
        QTableWidgetItem.setData(role,value)
        if(role == Qt.EditRole):
            self.setDirty()

    def data(self,role):
        if role == Qt.DisplayRole :
            if self.value.isValid():
                return self.value.toString()
            else:
                return "####"

        elif (role == Qt.TextAlignmentRole):
            if (self.value.type() == QVariant.String):
                return int(Qt.AlignLeft | Qt.AlignVCenter)
            else:
                return int(Qt.AlignRight | Qt.AlignVCenter)
        else:
            return QTableWidgetItem.data(role)

    # def setFormula(self, &formula):
    def setFormula(self, formula):
        self.setData(Qt.EditRole, formula)

    def formula(self) :
        return self.data(Qt.EditRole).toString()


    def setDirty(self):
        self.cacheIsDirty = True


    def value(self) :

        if (self.cacheIsDirty):
            self.cacheIsDirty = False

            formulaStr = self.formula()
            if (formulaStr.startsWith('\'')):
                self.cachedValue = formulaStr.mid(1)
            elif (formulaStr.startsWith('=')):
                self.cachedValue = self.Invalid
                expr = QString(formulaStr.mid(1))
                expr.replace(" ", "")
                expr.append(QChar.Null)

                pos = int(0)
                cachedValue = self.evalExpression(expr, pos)
                if (expr[pos] != QChar.Null):
                    cachedValue = self.Invalid
            else:
                pass
                ok = bool(False)
                # double d = formulaStr.toDouble(&ok)
                # if (ok)
                #     cachedValue = d
                #  else
                #     cachedValue = formulaStr
                #


        return self.cachedValue


    # def evalExpression(const QString &str, int &pos) const
    def evalExpression(self,str, pos):

        result = QVariant(self.evalTerm(str, pos))
        # while (str[pos] != QChar.Null):
        #     op = QChar(str[pos])
        #     if (op != '+' && op != '-'):
        #         return result
        #     pos = pos + 1
        #
        #     term = QVariant(self.evalTerm(str, pos))
        #     if (result.type() == QVariant.Double
        #             && term.type() == QVariant.Double)
        #         if (op == '+')
        #             result = result.toDouble() + term.toDouble()
        #          else
        #             result = result.toDouble() - term.toDouble()
        #
        #      else
        #         result = Invalid


        return QVariant(result)


    # QVariant Cell.evalTerm(const QString &str, int &pos) const
    def evalTerm(self,str, pos) :
        pass
        #
        # QVariant result = evalFactor(str, pos)
        # while (str[pos] != QChar.Null)
        #     QChar op = str[pos]
        #     if (op != '*' && op != '/')
        #         return result
        #     ++pos
        #
        #     QVariant factor = evalFactor(str, pos)
        #     if (result.type() == QVariant.Double
        #             && factor.type() == QVariant.Double)
        #         if (op == '*')
        #             result = result.toDouble() * factor.toDouble()
        #          else
        #             if (factor.toDouble() == 0.0)
        #                 result = Invalid
        #              else
        #                 result = result.toDouble() / factor.toDouble()
        #
        #
        #      else
        #         result = Invalid
        #

        # return result
        return QVariant(0)

    # QVariant Cell.evalFactor(const QString &str, int &pos) const
    def evalFactor(self,str, pos) :
        #
        # QVariant result
        # bool negative = false
        #
        # if (str[pos] == '-')
        #     negative = true
        #     ++pos
        #
        #
        # if (str[pos] == '(')
        #     ++pos
        #     result = evalExpression(str, pos)
        #     if (str[pos] != ')')
        #         result = Invalid
        #     ++pos
        #  else
        #     QRegExp regExp("[A-Za-z][1-9][0-9]0,2")
        #     QString token
        #
        #     while (str[pos].isLetterOrNumber() || str[pos] == '.')
        #         token += str[pos]
        #         ++pos
        #
        #
        #     if (regExp.exactMatch(token))
        #         int column = token[0].toUpper().unicode() - 'A'
        #         int row = token.mid(1).toInt() - 1
        #
        #         Cell *c = static_cast<Cell *>(
        #                           tableWidget()->item(row, column))
        #         if (c)
        #             result = c->value()
        #          else
        #             result = 0.0
        #
        #      else
        #         bool ok
        #         result = token.toDouble(&ok)
        #         if (!ok)
        #             result = Invalid
        #
        #
        #
        # if (negative)
        #     if (result.type() == QVariant.Double)
        #         result = -result.toDouble()
        #      else
        #         result = Invalid
        #
        #
        # return result

        return QVariant(0)
예제 #37
0
 def headerData(self, section, orientation, role = Qt.DisplayRole):
     if role == Qt.DisplayRole and orientation == Qt.Horizontal:
         return self.headers[section]
     return QVariant()
예제 #38
0
파일: model.py 프로젝트: pars-linux/uludag
 def headerData(self, col, orientation, role):
     ''' Return Header data for given column '''
     if orientation == Qt.Horizontal and role == Qt.DisplayRole:
         return QVariant(self.headerdata[col])
     return QVariant()
예제 #39
0
 def setModelData(self, editor, model, index):
     if editor.hasAcceptableInput():
         model.setData(index, QVariant(editor.text()))
예제 #40
0
 def headerData(self, section, orientation, role):
     if orientation == Qt.Horizontal and role == Qt.DisplayRole:
         if section == COL_ESDC:
             return QVariant("ESDC")
         elif section == COL_TEXT:
             return QVariant("Text")
         elif section == COL_ALL_GROUNDINGS:
             return QVariant("All Groundings")
         elif section == COL_GROUNDINGS:
             return QVariant("Groundings")
         elif section == COL_PROBABILITY:
             return QVariant("Esdc Prob")
         elif section == COL_COST:
             return QVariant("Esdc Cost")
         elif section == COL_RECOMPUTED_PROBABILITY:
             return QVariant("Recomputed Prob")
         elif section == COL_RECOMPUTED_COST:
             return QVariant("Recomputed Cost")
         elif section == COL_OVERALL_COST:
             return QVariant("Overall Cost")
         elif section == COL_OVERALL_PROB:
             return QVariant("Overall Prob")
         elif section == COL_PHI_VALUE:
             return QVariant("Phi Value")
         else:
             raise ValueError("Bad id: %s" % section)
     else:
         return QVariant()
예제 #41
0
 def headerData(self, section, orientation, role):
     if orientation == Qt.Horizontal and role == Qt.DisplayRole:
         return ["Node", "Value"][section]
     return QVariant()
예제 #42
0
    def setContentList(self):

        url = QUrl(self.url())
        if not url.path().endsWith(u"/"):
            url.setPath(url.path() + u"/")

        base_url = self.url().toString()
        base_path = (url.path())

        self.open(self.ReadOnly | self.Unbuffered)
        content = (u"<html>\n"
                   u"<head>\n"
                   u"  <title>" + self.html(base_url) + u"</title>\n"
                   u'  <style type="text/css">\n'
                   u"  th { background-color: #aaaaaa;\n"
                   u"       color: black }\n"
                   u"  table { border: solid 1px #aaaaaa }\n"
                   u"  tr.odd { background-color: #dddddd;\n"
                   u"           color: black\n }\n"
                   u"  tr.even { background-color: white;\n"
                   u"           color: black\n }\n"
                   u"  </style>\n"
                   u"</head>\n\n"
                   u"<body>\n"
                   u"<h1>Listing for " + base_path + u"</h1>\n\n")

        lines = self.input.splitlines()

        for line in lines:

            pieces = line.split("\t")
            if pieces == ["."]:
                break
            try:
                type, path, host, port = pieces[:4]
            except ValueError:
                # This isn't a listing. Let's try returning data instead.
                self.setContentData()
                return

            if type[0] == "i":
                content += u"<p>" + self.html(type[1:]) + u"</p>"
            elif type[0] == "h" and path.startswith(u"URL:"):
                content += u"<p><a href=\"" + path[4:] + u"\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "0":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=text\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "1":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "4":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=binhex\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "5":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=dos\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "6":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=uuencoded\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "9":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "g":
                content += u"<img src=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</img>"
            elif type[0] == "I":
                content += u"<img src=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</img>"

        content += (u"</body>\n" u"</html>\n")

        self.content = content.encode("utf-8")

        self.setHeader(QNetworkRequest.ContentTypeHeader,
                       QVariant("text/html; charset=UTF-8"))
        self.setHeader(QNetworkRequest.ContentLengthHeader,
                       QVariant(len(self.content)))
        self.readyRead.emit()
        self.finished.emit()
예제 #43
0
 def setModelData(self, editor, model, index):
     model.setData(index, QVariant(editor.toSimpleHtml()))
예제 #44
0
    def __init__(self, parent):
        RWidget.__init__(self, parent)
        self.parent = parent
        self._hist = History(items=[])
        self._currentPlot = QVariant(QString())
        
        self.callLineEdit = QLineEdit()
        self.callLineEdit.setReadOnly(True)
        self.callLineEdit.setToolTip("Commands to reproduce plot")
        self.callLineEdit.setWhatsThis("Commands to reproduce plot")
        actions = []

#        playAction = QAction("Replay", self)
#        playAction.setStatusTip("Replay selected plot")
#        playAction.setToolTip("Replay selected plot")
#        playAction.setIcon(QIcon(":edit-copy"))
#        actions.append(playAction)
        
        firstAction = QAction("End", self)
        firstAction.setStatusTip("Move to end of history")
        firstAction.setToolTip("Move to end of history")
        firstAction.setIcon(QIcon(":go-first"))
        actions.append(firstAction)
        
        previousAction = QAction("Previous", self)
        previousAction.setStatusTip("Move to previous plot")
        previousAction.setToolTip("Move to previous plot")
        previousAction.setIcon(QIcon(":go-previous"))
        actions.append(previousAction)

        infoAction = QAction("Info", self)
        infoAction.setStatusTip("Show plot info")
        infoAction.setToolTip("Show plot info")
        infoAction.setIcon(QIcon(":gtk-info"))
        actions.append(infoAction)
        
        nextAction = QAction("Next", self)
        nextAction.setStatusTip("Move to next plot")
        nextAction.setToolTip("Move to next plot")
        nextAction.setIcon(QIcon(":go-next"))
        actions.append(nextAction)
        
        lastAction = QAction("Start", self)
        lastAction.setStatusTip("Move to latest plot")
        lastAction.setToolTip("Move to latest plot")
        lastAction.setIcon(QIcon(":go-last"))
        actions.append(lastAction)
        actions.append(None)
        
        clearAction = QAction("Clear", self)
        clearAction.setStatusTip("Clear plot history")
        clearAction.setToolTip("Clear plot history")
        clearAction.setIcon(QIcon(":edit-clear"))
        actions.append(clearAction)
        

        hbox = QHBoxLayout()
        for action in actions:
            if not action is None:
                button = QToolButton()
                button.setDefaultAction(action)
                button.setAutoRaise(True)
                hbox.addWidget(button)
            else:
                hbox.addWidget(self.callLineEdit)
        self.setLayout(hbox)

        self.connect(firstAction, SIGNAL("triggered()"), self.first)
        self.connect(previousAction, SIGNAL("triggered()"), self.previous)
        self.connect(infoAction, SIGNAL("triggered()"), self.info)
        self.connect(nextAction, SIGNAL("triggered()"), self.next)
        self.connect(lastAction, SIGNAL("triggered()"), self.last)
        self.connect(clearAction, SIGNAL("triggered()"), self.clear)
예제 #45
0
 def headerData(self, section, orientation, role):
     """ (override function) retrieve only column heading for display """
     if orientation == Qt.Horizontal and role == Qt.DisplayRole:
         return QVariant('')
     return None
예제 #46
0
	def __updateWorkunit(self, item, workunit):
		pixmap = QPixmap(":workunit.png")

		status = int(workunit['state'])
		try:
			done = int(float(workunit['active_task']['fraction_done']) * 100.0)
			processStatus = int(workunit['active_task']['active_task_state'])
		except KeyError:
			processStatus = -1
			done = 0

		try:
			suspViaGui = workunit['suspended_via_gui']
			suspViaGui = True
		except KeyError:
			suspViaGui = False

		zoznam = [QVariant(int(status)), QVariant(int(processStatus)), QVariant(int(done)), QVariant(bool(suspViaGui))]

		if zoznam == item.data(0, Qt.UserRole + 3).toList():
			return

		#pozor memory leak
		data = QVariant.fromList(zoznam)
		item.setData(0, Qt.UserRole + 3, data)

		emblem = None
		if status == 1:
			emblem = QPixmap(":status_downloading.png")
			item.setData(0, Qt.UserRole + 2, QVariant(3))
			self.__setProgressPixmapInactive(pixmap)
		elif status == 2:
			if processStatus == 1:
				emblem = QPixmap(":status_running.png")
				item.setData(0, Qt.UserRole + 2, QVariant(0))
			elif (processStatus != -1) or (processStatus == 9):
				emblem = QPixmap(":status_suspended.png")
				item.setData(0, Qt.UserRole + 2, QVariant(4))
			else:
				item.setData(0, Qt.UserRole + 2, QVariant(5))
			if processStatus == -1:
				self.__setProgressPixmapInactive(pixmap)
			else:
				self.__modifyProgressPixmap(pixmap, done)

		elif status == 3:
			emblem = QPixmap(":status_error.png")
			item.setData(0, Qt.UserRole + 2, QVariant(7))
		elif status == 4:
			emblem = QPixmap(":status_uploading.png")
			item.setData(0, Qt.UserRole + 2, QVariant(1))
		elif status == 5:
			emblem = QPixmap(":status_uploaded.png")
			item.setData(0, Qt.UserRole + 2, QVariant(2))
		elif status == 6:
			emblem = QPixmap(":status_aborted.png")
			item.setData(0, Qt.UserRole + 2, QVariant(6))
		else:
			item.setData(0, Qt.UserRole + 2, QVariant(8))
			self.__setProgressPixmapInactive(pixmap)

		if (suspViaGui):
			emblem = QPixmap(":workunit_suspended.png")

		self.__addEmblem(pixmap, emblem)

		item.setData(0, Qt.DecorationRole, QVariant(QIcon(pixmap)))
예제 #47
0
파일: table.py 프로젝트: maximerobin/Ufwi
    def mousePressEvent(self, event):

        TableView.mousePressEvent(self, event)
        if event.button() != Qt.RightButton or not self.data:
            return

        index = self.indexAt(event.pos())
        # Cursor isn't on a row
        if not index.isValid():
            return

        if self.indexWidget(index):
            return

        # get data
        field = unicode(self.columns[index.column()])
        arg_data = self.model().data(self.model().index(index.row(), index.column(), self.rootIndex()), Qt.UserRole).toPyObject()

        # Create a menu to display all pages...
        menu = QMenu(self)

        copyAction = QAction(self.tr('Copy text'), self)
        self.connect(copyAction, SIGNAL('triggered()'), self.copySelection)
        menu.addAction(copyAction)

        if self.fragment.type != 'IDSIPSTable':
            packetinfoAction = QAction(self.tr('Packet details'), self)
            self.connect(packetinfoAction, SIGNAL('triggered()'), self._openPacketInfo)
            menu.addAction(packetinfoAction)

        for action in arg_data.actions():
            action.setParent(self)
            menu.addAction(action)

        menu.addSeparator()
        if self.current_page:
            pages = self.current_page.get_pagelinks(field, arg_data)
            if self.user_settings and pages:
                for page in pages:
                    title = self.user_settings['pages'].pages[page].title
                    action = QAction(tr('Open "%s" view') % title, self)

                    # Usefull data used when action is triggered
                    data = [page, field, unicode(arg_data.label), unicode(arg_data.value)]
                    data = QVariant(data)
                    # With PyQt 4.7.3, data type is List instead of StringList:
                    # force the cast to StringList
                    data.convert(QVariant.StringList)
                    action.setData(data)
                    menu.addAction(action)

        #if pages:
        #    menu.addSeparator()

        # And ask user if he wants to create a new page...
        #createPageAction = QAction(self.tr('Create a new view for this entity...'), self)
        #self.connect(createPageAction, SIGNAL("triggered()"), lambda: self.createPageEvent(field, arg_data.label, arg_data.value))
        #menu.addAction(createPageAction)

        self.connect(menu, SIGNAL('triggered(QAction*)'), self.loadPageEvent)

        menu.exec_(event.globalPos())