コード例 #1
0
    void testFindingTables()
    {
        // How to find all the tables in a QTextDocument?
        QTextDocument textDoc;
        QTextCursor c( &textDoc );
        QTextTable* firstTable = c.insertTable( 2, 2 );
        QTextTableCell bottomRight = firstTable->cellAt( 1, 1 );
        QTextTable* secondTable = bottomRight.firstCursorPosition().insertTable( 3, 3 ); // a nested table
        c.movePosition( QTextCursor::End );
        QTextTable* thirdTable = c.insertTable( 1, 1 );
        thirdTable->firstCursorPosition().insertText( "in table" );
        c.insertText( "Foo" );
        QList<QTextTable *> origTables;
        origTables << firstTable << secondTable << thirdTable;

        // A generic and slow solution is
        //    curs.currentTable() && !tablesFound.contains(curs.currentTable())
        // for each cursor position. Surely there's better.
        // We could jump to currentFrame().lastCursorPosition() but then it would skip
        // nested tables.
        QTextDocument* clonedDoc = textDoc.clone();
        QSet<QTextTable *> tablesFound;
        {
            QTextCursor curs(clonedDoc);
            while (!curs.atEnd()) {
                QTextTable* currentTable = curs.currentTable();
                if ( currentTable && !tablesFound.contains(currentTable) ) {
                    tablesFound.insert( currentTable );
                }
                curs.movePosition( QTextCursor::NextCharacter );
            }
            QCOMPARE( tablesFound.size(), 3 );
        }

        // Let's do something else then, let's find them by cursor position
        QList<QTextTable *> tablesByPos;
        {
            // first test
            const int firstPos = firstTable->firstCursorPosition().position();
            QTextCursor curs( clonedDoc );
            curs.setPosition( firstPos );
            QVERIFY( curs.currentTable() );

            // generic loop. works this approach is in TextDocument::breakTables now.
            Q_FOREACH( QTextTable* origTable, origTables ) {
                QTextCursor curs( clonedDoc );
                curs.setPosition( origTable->firstCursorPosition().position() );
                tablesByPos.append( curs.currentTable() );
            }
            QCOMPARE( tablesByPos.size(), 3 );
            QCOMPARE( tablesByPos.toSet(), tablesFound );
        }