3

编辑:我提供了一个答案,但我很乐意接受另一个提供解释的答案。

我进行了子类QPushButton化以添加一些功能,但是在将clicked信号连接到插槽后,它不会被调用。如果我使用香草 QPushButton,并且不更改任何其他内容,它就可以工作。这是代码:

/// --- 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;
}

这就是我连接信号的方式:

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
}

这里可能有什么问题?

4

2 回答 2

3

QPushButton::mousePressEvent(e)在覆盖的MouseRelease3vent方法中意外调用。

于 2010-07-31T20:16:11.493 回答
0

我终于解决了。解决方案是emit clicked();在 MouseReleaseEvent 中添加一行。

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

我仍然不知道为什么对超类的 mousePressEvent 的调用没有解决这个问题。无论如何,它有效。

于 2010-07-31T15:15:42.523 回答