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

前端 未结 5 1981
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 05:52

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

5条回答
  •  粉色の甜心
    2020-12-10 06:21

    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.

提交回复
热议问题