Search code examples
c++qtqtexteditbulletedlistnumbered

How to create a bulleted or numbered list with Qt?


How to create a bulleted or numbered list in QTextEdit with Qt by clicking a button? Also it is necessary that make a list the paragraphes which are selected by clicking the same button. And when the cursor is in the list and you click the button, the the list item becomes not-list item, but a simple paragraph. In two words I want to create for my text editer 2 buttons, that work in the same way as (buletting and numbering button is MS Word).


Solution

  • I have used this code:

     void TextEdit::textStyle(int styleIndex)
     {
         QTextCursor cursor = textEdit->textCursor();
    
         if (styleIndex != 0) {
             QTextListFormat::Style style = QTextListFormat::ListDisc;
    
             switch (styleIndex) {
                 default:
                 case 1:
                     style = QTextListFormat::ListDisc;
                     break;
                 case 2:
                     style = QTextListFormat::ListCircle;
                     break;
                 case 3:
                     style = QTextListFormat::ListSquare;
                     break;
                 case 4:
                     style = QTextListFormat::ListDecimal;
                     break;
                 case 5:
                     style = QTextListFormat::ListLowerAlpha;
                     break;
                 case 6:
                     style = QTextListFormat::ListUpperAlpha;
                     break;
                 case 7:
                     style = QTextListFormat::ListLowerRoman;
                     break;
                 case 8:
                     style = QTextListFormat::ListUpperRoman;
                     break;
             }
    
             cursor.beginEditBlock();
    
             QTextBlockFormat blockFmt = cursor.blockFormat();
    
             QTextListFormat listFmt;
    
             if (cursor.currentList()) {
                 listFmt = cursor.currentList()->format();
             } else {
                 listFmt.setIndent(blockFmt.indent() + 1);
                 blockFmt.setIndent(0);
                 cursor.setBlockFormat(blockFmt);
             }
    
             listFmt.setStyle(style);
    
             cursor.createList(listFmt);
    
             cursor.endEditBlock();
         } else {
             // ####
             QTextBlockFormat bfmt;
             bfmt.setObjectIndex(-1);
             cursor.mergeBlockFormat(bfmt);
         }
     }
    

    from this source.

    Only I have changed

     } else {
         // ####
         QTextBlockFormat bfmt;
         bfmt.setObjectIndex(-1);
         cursor.mergeBlockFormat(bfmt);
     }
    

    to the following code:

     } else {
         // ####
    QTextBlockFormat bfmt;
    bfmt.setObjectIndex(0);
    cursor.mergeBlockFormat(bfmt);
    setTextCursor(cursor);
    }