QEvent信号和插槽

时间:2015-04-28 08:44:48

标签: c++ qt signals-slots qpushbutton qevent

我创建了一个Qt项目,我添加了一个QPushButton,其样式我用QEvent和QMouseEvent定制。我在这个按钮上添加了一个插槽,但它不起作用。 这是一个像我这样的项目:

标题1:

#ifndef MYQPUSHBUTTON_H
#define MYQPUSHBUTTON_H

#include <QPushButton>
#include <QPalette>

class myQPushButton : public QPushButton
{
Q_OBJECT
public:
explicit myQPushButton(QWidget *parent = 0);
~myQPushButton();
void enterEvent(QEvent* );
void leaveEvent(QEvent* );
void mousePressEvent(QMouseEvent *  );
void mouseReleaseEvent(QMouseEvent *  );

signals:

public slots:

private:
QPalette *palette;
};

#endif // MYQPUSHBUTTON_H

标题2:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "myQPushButton/myqpushbutton.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
myQPushButton *button;
};

#endif // MAINWINDOW_H

来源1:

#include "myqpushbutton.h"

myQPushButton::myQPushButton(QWidget *parent) :
QPushButton(parent)
{
setFixedSize(200,200);
setIconSize(QSize(200,200));
setIcon(QIcon("D:/clockbox/qt/clockbox/exit_button_wwin_norm.png"));
setFlat(true);

}

myQPushButton::~myQPushButton()
{

}

void myQPushButton::enterEvent(QEvent* )
 {
setIcon(QIcon("D:/clockbox/qt/clockbox/exit_button_wwin_enter.png"));
 }

 void myQPushButton::leaveEvent(QEvent* )
 {
setIcon(QIcon("D:/clockbox/qt/clockbox/exit_button_wwin_norm.png"));
 }

 void myQPushButton::mousePressEvent(QMouseEvent * )
 {
setIcon(QIcon("D:/clockbox/qt/clockbox/exit_button_wwin_pressed.png"));
 }

 void myQPushButton::mouseReleaseEvent(QMouseEvent * )
 {
setIcon(QIcon("D:/clockbox/qt/clockbox/exit_button_wwin_enter.png"));
 }

来源2:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
myQPushButton y;
QObject::connect(y, SIGNAL(clicked()), &w, SLOT(close()));

return a.exec();
}

来源3:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
button = new myQPushButton(this);
setCentralWidget(button);
}

MainWindow::~MainWindow()
{
delete ui;
}

我在源2上遇到此错误:

错误:没有匹配函数来调用'QObject :: connect(myQPushButton&amp;,const char *,MainWindow *,const char *)'   QObject :: connect(y,SIGNAL(clicked()),&amp; w,SLOT(close()));                                                           ^

我希望此按钮成为退出按钮。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

要克服编译错误,您必须将第QObject::connect(y, SIGNAL(clicked()), &w, SLOT(close()));行更改为QObject::connect(&y, SIGNAL(clicked()), &w, SLOT(close()));QObject::connect需要发件人的指针。

但这不是问题所在,您是从实际未添加到窗口的按钮添加信号(您创建了连接到y插槽的按钮close {1}}但稍后在main()中您创建了一个新按钮并将其添加到MainWindow作为中央窗口小部件。然后您应该从MainWindow中删除该按钮并执行{{1像main()一样调用QObject::connect

MainWindow::MainWindow

主:

QObject::connect(button, SIGNAL(clicked()), this, SLOT(close()));