Exemplo n.º 1
0
def getTooltipValue( value ):
    """ Takes a potentially multilined string and converts it to
        the form suitable for tooltips """

    value = str( value )
    if Qt.mightBeRichText( value ):
        tooltipValue = str( Qt.escape( value ) )
    else:
        tooltipValue = value

    lines = tooltipValue.splitlines()
    lineCount = len( lines )
    if lineCount > 1:
        value = ""
        index = 0
        for line in lines:
            if index >= 5:  # First 5 lines only
                break
            if index > 0:
                value += "\n"
            if len( line ) > 128:
                value += line[ : 128 ] + "<...>"
            else:
                value += line
            index += 1
        if lineCount > 5:
            value += "\n<...>"
    elif lineCount == 1:
        if len( lines[ 0 ] ) > 128:
            value = lines[ 0 ][ : 128 ] + "<...>"
        else:
            value = lines[ 0 ]

    return value
Exemplo n.º 2
0
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
Exemplo n.º 3
0
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
Exemplo n.º 4
0
    def contentToHTMLWithAnAdditionalColumn(self, columnRoleList=None, titles=None, fontSize=8, additionalCol=None,
                                            additionalColTitle=None):
        if not additionalCol:
            additionalCol = {}
        if not additionalColTitle:
            additionalColTitle = []
        model = self.model()
        cols = model.cols()
        if columnRoleList is None:
            columnRoleList = [None if self.isColumnHidden(idx) else Qt.DisplayRole
                              for idx in xrange(len(cols))]
        columnRoleList.extend([Qt.DisplayRole for i in xrange(len(additionalCol))])

        if titles is None:
            titles = [None] * len(cols)

        QtGui.qApp.startProgressBar(model.rowCount())
        try:
            doc = QtGui.QTextDocument()
            cursor = QtGui.QTextCursor(doc)

            headerFormat = QtGui.QTextCharFormat()
            headerFormat.setFontWeight(QtGui.QFont.Bold)
            headerFormat.setFontPointSize(fontSize + 4)
            bodyFormat = QtGui.QTextCharFormat()
            bodyFormat.setFontPointSize(fontSize)
            tableFormat = QtGui.QTextCharFormat()
            tableFormat.setFontPointSize(fontSize)

            cursor.setCharFormat(headerFormat)
            header = self.reportHeader()
            if Qt.mightBeRichText(header):
                cursor.insertHtml(header)
            else:
                cursor.insertText(header)
            cursor.insertBlock()
            cursor.setCharFormat(bodyFormat)
            description = self.reportDescription()
            if Qt.mightBeRichText(description):
                cursor.insertHtml(description)
            else:
                cursor.insertText(description)
            cursor.insertBlock()

            colWidths  = [ self.columnWidth(i) for i in xrange(len(cols) + len(additionalCol)) ]
            totalWidth = sum(colWidths)
            tableColumns = [('10?', [u'№'], CReportBase.AlignRight)]
            tempAddColTitleList = []
            for iCol, colWidth in enumerate(colWidths):
                widthInPercents = str(max(1, colWidth*100./totalWidth))+'?'
                if columnRoleList[iCol] is None:
                    continue
                blockFormat = QtGui.QTextBlockFormat()
                if iCol < len(cols):
                    col = cols[iCol]
                    colAlingment = Qt.AlignHorizontal_Mask & forceInt(col.alignment())
                    blockFormat.setAlignment(Qt.AlignmentFlag(colAlingment))
                    columnTitle = forceString(titles[iCol] if isinstance(titles[iCol], basestring) else col.title())
                else:
                    blockFormat.setAlignment(Qt.AlignCenter)
                    i = 0
                    for key in additionalColTitle:
                        if additionalCol.has_key(key):
                            columnTitle = key
                            if i == iCol - len(cols):
                                break
                            i += 1
                    tempAddColTitleList.append(columnTitle)
                tableColumns.append((widthInPercents, [columnTitle], blockFormat))

            table = createTable(cursor, tableColumns, 1, 1, 2, 0, tableFormat)
            for iModelRow in xrange(model.rowCount()):
                QtGui.qApp.stepProgressBar()
                QtGui.qApp.processEvents(QEventLoop.ExcludeUserInputEvents)
                iTableRow = table.addRow()
                table.setText(iTableRow, 0, iModelRow + 1, tableFormat)
                iTableCol = 1
                for iModelCol in xrange(len(cols)):
                    columnRole = columnRoleList[iModelCol]
                    if columnRole is None:
                        continue
                    index = model.index(iModelRow, iModelCol)
                    text = forceString(model.data(index, role = columnRole))
                    table.setText(iTableRow, iTableCol, text, tableFormat)
                    iTableCol += 1
                try:
                    eventId = forceInt(model.items[iTableRow - 1].get('eventId'))
                except:
                    eventId = ''
                for iAddCol in xrange(len(additionalCol)):
                    tempList = additionalCol.get(tempAddColTitleList[iAddCol])
                    if tempList.has_key(eventId):
                        rowText = tempList.get(eventId)
                    else:
                        rowText = ''
                    table.setText(iTableRow, iTableCol + iAddCol, rowText, tableFormat)

            return doc
        finally:
            QtGui.qApp.stopProgressBar()
Exemplo n.º 5
0
    def contentToHTML(self, columnRoleList=None, titles = None, fontSize = 8):
        u"""
        Переводит содержимое таблицы в экземляр класса QTextDocument (atronah: странная логика названия)
        :param columnRoleList: список с ролями данных для каждого столбца.
            Если роль для столбца не указана, то он не выводится, иначе выводятся данные, полученные для этой роли.
            Если вместо списка передано None, то отображаются все видимые столбцы модели.
        :param titles: список заголовков столбцов. Если задан, то данное имя используется для столбца в
            HTML-представлении, если None, то используется заголовок из модели.
        :param fontSize:
        :return:
        """
        model = self.model()
        cols = model.cols()
        if columnRoleList is None:
            columnRoleList = [None if self.isColumnHidden(idx) else Qt.DisplayRole 
                              for idx in xrange(len(cols))]
        
        if titles is None:
            titles = [None] * len(cols)
        
        QtGui.qApp.startProgressBar(model.rowCount())
        try:
            doc = QtGui.QTextDocument()
            cursor = QtGui.QTextCursor(doc)

            headerFormat = QtGui.QTextCharFormat()
            headerFormat.setFontWeight(QtGui.QFont.Bold)
            headerFormat.setFontPointSize(fontSize + 4)
            bodyFormat = QtGui.QTextCharFormat()
            bodyFormat.setFontPointSize(fontSize)
            tableFormat = QtGui.QTextCharFormat()
            tableFormat.setFontPointSize(fontSize)

            cursor.setCharFormat(headerFormat)
            header = self.reportHeader()
            if Qt.mightBeRichText(header):
                cursor.insertHtml(header)
            else:
                cursor.insertText(header)
            cursor.insertBlock()
            cursor.setCharFormat(bodyFormat)
            description = self.reportDescription()
            if Qt.mightBeRichText(description):
                cursor.insertHtml(description)
            else:
                cursor.insertText(description)
            cursor.insertBlock()

            colWidths  = [ self.columnWidth(i) for i in xrange(len(cols)) ]
            totalWidth = sum(colWidths)
            tableColumns = [('10?', [u'№'], CReportBase.AlignRight)]
            for iCol, colWidth in enumerate(colWidths):
                widthInPercents = str(max(1, colWidth*100./totalWidth))+'?'
                if columnRoleList[iCol] is None:
                    continue
                col = cols[iCol]
                colAlingment = Qt.AlignHorizontal_Mask & forceInt(col.alignment())
                blockFormat = QtGui.QTextBlockFormat()
                blockFormat.setAlignment(Qt.AlignmentFlag(colAlingment))
                columnTitle = forceString(titles[iCol] if isinstance(titles[iCol], basestring) else col.title())
                tableColumns.append((widthInPercents, [columnTitle], blockFormat))

            table = createTable(cursor, tableColumns, 1, 1, 2, 0, tableFormat)
            for iModelRow in xrange(model.rowCount()):
                QtGui.qApp.stepProgressBar()
                QtGui.qApp.processEvents(QEventLoop.ExcludeUserInputEvents)
                iTableRow = table.addRow()
                table.setText(iTableRow, 0, iModelRow + 1, tableFormat)
                iTableCol = 1
                for iModelCol in xrange(len(cols)):
                    columnRole = columnRoleList[iModelCol]
                    if columnRole is None:
                        continue
                    index = model.index(iModelRow, iModelCol)
                    text = forceString(model.data(index, role = columnRole))
                    table.setText(iTableRow, iTableCol, text, tableFormat)
                    iTableCol += 1

            return doc
        finally:
            QtGui.qApp.stopProgressBar()