How to center text in a QTextTable

Im developing applications with qt framework, and now I want to save my tabular data in pdf. I use the QTextTable and QTextDocument classes. However, I cannot select the text in the cells. How should I do it?

Thanks for the help.

+3
source share
4 answers

If you want to align when inserting text, you can call this function with alignment = Qt: AlignHCenter. You can change the function to also indicate character formatting.

// Insert text with specified alignment in specified cell
void insertAlignedText(QTextTable *table, int row, int col, Qt::Alignment alignment, QString text)
{
    // Obtain cursor and current block format
    QTextCursor textCursor = table->cellAt(row,col).firstCursorPosition();    
    QTextBlockFormat blockFormat = textCursor.blockFormat();

    // Read vertical part of current alignment flags
    Qt::Alignment vertAlign = blockFormat.alignment() & Qt::AlignVertical_Mask;

    // Mask out vertical part of specified alignment flags
    Qt::Alignment horzAlign = alignment & Qt::AlignHorizontal_Mask;

    // Combine current vertical and specified horizontal alignment
    Qt::Alignment combAlign = horzAlign | vertAlign;

    // Apply and write
    blockFormat.setAlignment(combAlign);    
    textCursor.setBlockFormat(blockFormat);
    textCursor.insertText(text);
}
+5
source
QTextBlockFormat centerAlignment;
centerAlignment.setAlignment(Qt::AlignHCenter);

cursor = table->cellAt(row, column).firstCursorPosition();
cursor.setBlockFormat(centerAlignment);
cursor.insertText("Hello, this is my first post here!");

, , , . , , , , , ​​, QTextCursor:: setBlockFormat() , .

+1

If you want to change the alignment after the text has been recorded, you can use the following alignment function = Qt: AlignHCenter.

// Modify horizontal alignment of text in specified cell
void modifyTextAlignment(QTextTable *table, int row, int col, Qt::Alignment alignment)
{
    // Obtain cursor and current block format
    QTextCursor textCursor = table->cellAt(row,col).firstCursorPosition();   
    textCursor.select(QTextCursor::BlockUnderCursor);
    QTextBlockFormat blockFormat = textCursor.blockFormat();

    // Read vertical part of current alignment flags
    Qt::Alignment vertAlign = blockFormat.alignment() & Qt::AlignVertical_Mask;

    // Mask out vertical part of specified alignment flags
    Qt::Alignment horzAlign = alignment & Qt::AlignHorizontal_Mask;

    // Combine current vertical and specified horizontal alignment
    Qt::Alignment combAlign = horzAlign | vertAlign;

    // Apply
    blockFormat.setAlignment(combAlign);    
    textCursor.setBlockFormat(blockFormat);
}
0
source

Source: https://habr.com/ru/post/1796160/


All Articles