Subclassing QLabel to show native 'Mouse Hover Button indicator'

后端 未结 2 831
既然无缘
既然无缘 2021-01-03 09:49

I have a QLabel with a \'StyledPanel, raised\' frame.
It is clickable, by subclassing QLabel;

class InteractiveLabel(QtGui.QLabel):
    def __init__(self         


        
2条回答
  •  [愿得一人]
    2021-01-03 10:31

    @Lol4t0, i have some improvements for your method...

    This is my header file:

    #ifndef QLABELEDPUSHBUTTON_H
    #define QLABELEDPUSHBUTTON_H
    
    #include 
    
    class QLabel;
    
    class QLabeledPushButton : public QPushButton
    {
        Q_OBJECT
    
        QLabel * m_label;
    
    public:
        QLabeledPushButton(QWidget * parent = 0);
    
        QString text() const;
        void setText(const QString & text);
    
    protected:
        void resizeEvent(QResizeEvent * event);
    };
    
    #endif // QLABELEDPUSHBUTTON_H
    

    And there is my cpp file:

    #include 
    #include 
    #include 
    #include "QLabeledPushButton.h"
    
    QLabeledPushButton::QLabeledPushButton(QWidget * parent)
        : QPushButton(parent)
        , m_label(new QLabel(this))
    {
        m_label->setWordWrap(true);
        m_label->setMouseTracking(false);
        m_label->setAlignment(Qt::AlignCenter);
        m_label->setTextInteractionFlags(Qt::NoTextInteraction);
        m_label->setGeometry(QRect(4, 4, width()-8, height()-8));
    }
    
    QString QLabeledPushButton::text() const
    {
        return m_label->text();
    }
    
    void QLabeledPushButton::setText(const QString & text)
    {
        m_label->setText(text);
    }
    
    void QLabeledPushButton::resizeEvent(QResizeEvent * event)
    {
        if (width()-8 < m_label->sizeHint().width())
            setMinimumWidth(event->oldSize().width());
        if (height()-8 < m_label->sizeHint().height())
            setMinimumHeight(event->oldSize().height());
    
        m_label->setGeometry(QRect(4, 4, width()-8, height()-8));
    }
    

    So text on QLabel is always visible. QPushButton can't be too small to hide part of text. I think this way is more comfortable to use...

提交回复
热议问题