Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to enable word wrapping of text on some simple widgets like QPushButton?

Tags:

word-wrap

qt

I'd like to make QPushButton word wrap and expand it's height instead of expanding width. How can I do that?

like image 996
Septagram Avatar asked Jan 23 '12 08:01

Septagram


4 Answers

A straightforward solution is to insert a line break when writing the text inside the QPushButton just like

This button has \n a long text

If you are digning in QtDesigner, you can simply right-click the button and then "Insert line break"

like image 161
Alejandro J Avatar answered Oct 05 '22 16:10

Alejandro J


I have solved the problem with wordwrap on a button this way:

QPushButton *createQPushButtonWithWordWrap(QWidget *parent, const QString &text)
{
   auto btn = new QPushButton(parent);
   auto label = new QLabel(text,btn);
   label->setWordWrap(true);

   auto layout = new QHBoxLayout(btn);
   layout->addWidget(label,0,Qt::AlignCenter);

   return btn;
}
like image 45
user10283628 Avatar answered Oct 05 '22 18:10

user10283628


For word wrapping in regular QPushButton you can implement proxy style class derived from QProxyStyle.

/**
proxy style for text wrapping in pushbutton
*/
class QtPushButtonStyleProxy : public QProxyStyle
{
public:
    /**
    Default constructor.
    */
    QtPushButtonStyleProxy()
        : QProxyStyle()
    {
    }

    virtual void drawItemText(QPainter *painter, const QRect &rect,
        int flags, const QPalette &pal, bool enabled,
        const QString &text, QPalette::ColorRole textRole) const
    {
        flags |= Qt::TextWordWrap;    
        QProxyStyle::drawItemText(painter, rect, flags, pal, enabled, text, textRole);
    }

private:
    Q_DISABLE_COPY(QtPushButtonStyleProxy)
};

And later in your own MyQtPushButton:

MyQtPushButton::MyQtPushButton()
   : QPushButton()
{
   setStyle(new QtPushButtonStyleProxy());
}

See additional information on QProxyStyle class in Qt documentation.

like image 45
Vitaly Gorokhov Avatar answered Oct 05 '22 18:10

Vitaly Gorokhov


You might be doing something wrong. Buttons aren't supposed to hold much text, rather a couple of words describing action to be taken. If you wish to make it multi-line, you'd better consider providing a QLabel with corresponding description.

Anyways, I don't know any [Qt-supported] way to make this. Same problem exists for, say, QHeaderView captions, where it could be even more applicable. Manually, you could always do this by adding "\n" chars to your caption strings (which you may automate for sure).

like image 31
mike.dld Avatar answered Oct 05 '22 16:10

mike.dld