コード例 #1
0
    def toTextDocument(self, fontSize=8):
        model = self.model()  # type: CItemListModel
        cols = model.cols()

        tableHeader = [forceString(col.title()) for col in 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)
            tableHeaderFormat = QtGui.QTextCharFormat()
            tableHeaderFormat.setFontPointSize(fontSize)
            tableHeaderFormat.setFontWeight(QtGui.QFont.Bold)
            tableBodyFormat = QtGui.QTextCharFormat()
            tableBodyFormat.setFontPointSize(fontSize)

            colWidths = [self.columnWidth(i) for i in xrange(len(cols))]
            totalWidth = sum(colWidths)

            cursor.setCharFormat(headerFormat)
            tableColumns = []
            for colIdx, colWidth in enumerate(colWidths):
                widthInPercents = str(max(1, colWidth * 100.0 / totalWidth)) + '?'
                col = cols[colIdx]
                colAlingment = Qt.AlignHorizontal_Mask & forceInt(col.alignment(None))
                blockFormat = QtGui.QTextBlockFormat()
                blockFormat.setAlignment(Qt.AlignmentFlag(colAlingment))
                tableColumns.append((widthInPercents, [tableHeader[colIdx]], blockFormat))

            table = createTable(cursor, tableColumns, 1, 1, 2, 0, tableHeaderFormat)
            for rowIdx in xrange(model.rowCount()):
                QtGui.qApp.stepProgressBar()
                QtGui.qApp.processEvents(QtCore.QEventLoop.ExcludeUserInputEvents)
                iTableRow = table.addRow()
                for colIdx in xrange(len(cols)):
                    text = forceString(model.data(model.index(rowIdx, colIdx)))
                    table.setText(iTableRow, colIdx, text, tableBodyFormat)

            return doc
        finally:
            QtGui.qApp.stopProgressBar()
コード例 #2
0
ファイル: TableView.py プロジェクト: dio4/vista_1
    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()
コード例 #3
0
ファイル: TableView.py プロジェクト: dio4/vista_1
    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()