How to resize an image in a QTextEdit?

后端 未结 2 1349
轻奢々
轻奢々 2021-02-06 15:47

How to click on the image, hold from a corner of it, and resize the image in the QTextEdit? Or at least how to get an image under cursor/that is selected in order to change widt

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 15:56

    Here how I have implemented:

    void AdvancedTextEdit::resizeImage()
    {
    
        QTextBlock currentBlock = m_textEdit->textCursor().block();
        QTextBlock::iterator it;
    
        for (it = currentBlock.begin(); !(it.atEnd()); ++it)
        {
    
                 QTextFragment fragment = it.fragment();
    
    
    
                 if (fragment.isValid())
                 {
    
                     if(fragment.charFormat().isImageFormat ())
                     {
                          QTextImageFormat newImageFormat = fragment.charFormat().toImageFormat();
    
                          QPair size = ResizeImageDialog::getNewSize(this, newImageFormat.width(), newImageFormat.height());
    
                          newImageFormat.setWidth(size.first);
                          newImageFormat.setHeight(size.second);
    
                          if (newImageFormat.isValid())
                          {
                              //QMessageBox::about(this, "Fragment", fragment.text());
                              //newImageFormat.setName(":/icons/text_bold.png");
                              QTextCursor helper = m_textEdit->textCursor();
    
                              helper.setPosition(fragment.position());
                              helper.setPosition(fragment.position() + fragment.length(),
                                                  QTextCursor::KeepAnchor);
                              helper.setCharFormat(newImageFormat);
                          }
                      }
                  }
           }
    }
    

    Of course I have implemented also the ResizeImageDialog dialog's getNewSize(this, newImageFormat.width(), newImageFormat.height()); function that gets the current size of image and lets user to chnage the size, and returns the new size of image as a QPair. This is not hard to do. See here for the implementation of the dialog.

提交回复
热议问题