c++qtqwidgetqlabel

How to enable QLabel character wrapping(Not Word Wrapping) in QWidget C++?


I tried the word Wrap option in QLabel, but it wraps second word of "Hello World" on next line when size of label shrinks, I need to wrap the single word like "Hello" on character basis when size shrinks and when size expand it should be normal.

Is there is any option available to do this?


Solution

  • The following is untested but will, I think, give you roughly what you're looking for.

    class label: public QLabel {
      using super = QLabel;
    public:
      explicit label (const QString &text, QWidget *parent = nullptr)
        : super(text, parent)
        {}
    protected:
      virtual void paintEvent (QPaintEvent *event) override
        {
          QPainter painter(this);
          QTextOption opt;
    
          /*
           * Let the QPainter know it's allowed to wrap anywhere.
           */
          opt.setWrapMode(QTextOption::WrapAnywhere);
          painter.drawText(rect(), text(), opt);
        }
    };