PDA

View Full Version : Printing an entire QTreeWidget



bday1223
12th July 2015, 03:03
I'm trying to print all of the visible (non-hidden) items in A QTreeWidget. I can successfully print the current viewport, but I'd like to be able to print all of the items in the tree.

Any suggestions? Thanks.

d_stranz
12th July 2015, 18:54
// Pseudocode, sort of:

void printTreeItem( QTreeWidgetItem * pItem, int indentLevel )
{
if ( pItem && !pItem->isHidden() )
{
int nCols = pItem->columnCount();
for ( int nCol = 0; nCol < nCols; ++nCol )
printIndented( pItem->text( nCol ), indentLevel, nCol, nCols );

int nKids = pItem->childCount();
for ( int nKid = 0; nKid < nKids; ++nKid )
printTreeItem( child( nKid ), indentLevel + 1 );
}
}

void printTree( QTreeWidget * pTree )
{
int nTops = pTree->topLevelItemCount();
for ( int nTop = 0; nTop < nTops; ++nTop )
printTreeItem( pTree->topLevelItem( nTop ), 0 );
}


I'll let you figure out how to implement this:


printIndented( pItem->text( nCol ), indentLevel, nCol, nCols );

bday1223
14th July 2015, 01:24
Thanks.

So the idea is to just dump the tree to a text widget? I was kind of just hoping that there would be a convenient way to preserve the formatting, column widths, etc.

anda_skoa
14th July 2015, 12:07
How do you currently print?

Cheers,
_

d_stranz
14th July 2015, 16:35
So the idea is to just dump the tree to a text widget?

No. What I wrote simply recurses through the tree, and for each non-hidden item, extracting its text, "printing" it, then recursing into its non-hidden children. Sort of the tree widget version of pretty-printing.

If you want to preserve formatting, then your "print" routine is going to have to pull out those other properties - fonts, colors, backgrounds, icons, etc. and "print" them as well. I don't know how you handle column widths - the tree widget's column widths are going to be in screen pixels, not print pixels, so you'll need to figure out how to map that to the equivalent in paper pixels. (In the code I wrote, the "indent level" is equivalent to the column widths - if you determine the column widths in advance and put them into a vector, the indent level is just the index into the vector).

You might be able to do this with QTextDocument but I think that is going to be a lot harder to implement.

bday1223
16th July 2015, 02:30
That's exactly what I ended up doing - creating a QTextDocument, inserting a table, and copying from the tree to the table.
Thanks again.

d_stranz
16th July 2015, 17:29
creating a QTextDocument, inserting a table, and copying from the tree to the table

So long as you don't want any of the tree decorations (eg. lines from top level items to children, etc.) this is a perfectly reasonable way to do it.