Qt Signal Inheritance?

EDIT . I gave an answer, but I would be glad to accept another one that gives an explanation.

I subclassed QPushButtonto add some features, but after connecting the signal clickedto the slot, it will not be called. If I use vanilla QPushButton and don't change anything, it works. Here is the code:

/// --- imagebutton.h

#ifndef IMAGEBUTTON_H
#define IMAGEBUTTON_H

#include <QPushButton>
#include <QImage>

enum ButtonState
{
    Normal,
    MouseOver,
    Pushed
};

class ImageButton : public QPushButton
{
    Q_OBJECT
private:
    ButtonState state;

public:
    QImage *NormalImage;
    QImage *MouseOverImage;
    QImage *PushedImage;

public:
    explicit ImageButton(QWidget *parent = 0);
    virtual ~ImageButton();
    void enterEvent(QEvent *e);
    void leaveEvent(QEvent *e);
    void mousePressEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);
    void paintEvent(QPaintEvent *e);

signals:

public slots:

};

#endif // IMAGEBUTTON_H

/// --- imagebutton.cpp

#include <QPainter>

#include "imagebutton.h"

ImageButton::ImageButton(QWidget *parent) :
    QPushButton(parent)
{
    state = Normal;
}

void ImageButton::enterEvent(QEvent *e)
{
    QPushButton::enterEvent(e);
    state = MouseOver;
    this->repaint();
}

void ImageButton::leaveEvent(QEvent *e)
{
    QPushButton::leaveEvent(e);
    state = Normal;
    this->repaint();
}

void ImageButton::mousePressEvent(QMouseEvent *e)
{
    QPushButton::mousePressEvent(e);
    state = Pushed;
    this->repaint();
}

void ImageButton::mouseReleaseEvent(QMouseEvent *e)
{
    QPushButton::mousePressEvent(e);
    state = MouseOver;
    this->repaint();
}

void ImageButton::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);

    QImage *pic = NULL;

    switch (state)
    {
    case Normal:
        pic = NormalImage;
        break;
    case MouseOver:
        pic = MouseOverImage;
        break;
    case Pushed:
        pic = PushedImage;
        break;
    default:
        pic = NormalImage;
        break;
    }

    painter.drawImage(0, 0, *pic);
}

ImageButton::~ImageButton()
{
    delete NormalImage;
    delete MouseOverImage;
    delete PushedImage;
}

And this is how I connect the signal:

void MainWindow::initInterface()
{
    ImageButton *btn_start = new ImageButton(ui->page);
    btn_start->setText("start");
    connect(btn_start, SIGNAL(clicked()), this, SLOT(btn_clicked()));
    // more buttons connected to the same slot
}

What could be the problem?

+3
source share
2 answers

You accidentally call QPushButton::mousePressEvent(e)your overriden method MouseRelease3vent.

+3
source

I finally decided it. The solution was to put the string emit clicked();in MouseReleaseEvent.

void ImageButton::mouseReleaseEvent(QMouseEvent *e)
{
    QPushButton::mousePressEvent(e);
    state = MouseOver;
    emit clicked();
    this->repaint();
}

, mousePressEvent . , .

0

Source: https://habr.com/ru/post/1757470/


All Articles