#ifndef _MYBUTTON_H
#define _MYBUTTON_H
#include <QPushButton>
class MyButton:public QPushButton
{
Q_OBJECT//
只有加入了Q_OBJECT,你才能使用QT中的signal和slot机制。
public:
explicit MyButton(const QString& text,
QWidget *parent);
signals:
void clickedWithText(const QString text);
private slots:
void onSelfClicked();
};
#endif
#include "MyButton.h"
MyButton::MyButton(const QString& text,
QWidget *parent)
:QPushButton(text,parent)
{
connect(this,SIGNAL(clicked()),
this,SLOT(onSelfClicked()));
}
// void clickedWithText(const QString text);
void MyButton::onSelfClicked()
{
emit clickedWithText(this->text());
}#ifndef _MYWINDOW_H
#define _MYWINDOW_H
#include <QWidget>
//#include <QPushButton>
#include "MyButton.h"
#include <QLabel>
#include <QVaBoxLayout>
#include <QHBoxLayout>
class MyWindow:public QWidget
{
Q_OBJECT
private:
QLabel *lb_show;
MyButton *btn_A;
MyButton *btn_B;
MyButton *btn_C;
QVBoxLayout *mainLayout;
QHBoxLayout *keyLayout;
public:
explicit MyWindow(QWidget* parent = 0);
private slots:
void onClicked(QString text);
void onAClicked();
void onBClicked();
void onCClicked();
};
#endif #include "MyWindow.h"
MyWindow::MyWindow(QWidget* parent)
:QWidget(parent)
{
lb_show =new QLabel("",this);
btn_A = new MyButton("A",this);
btn_B = new MyButton("B",this);
btn_C = new MyButton("C",this);
QWidget *keyWidget = new QWidget(this);
mainLayout =new QVBoxLayout(this);
keyLayout =new QHBoxLayout(this);
keyLayout ->addWidget(btn_A);
keyLayout ->addWidget(btn_B);
keyLayout ->addWidget(btn_C);
keyWidget ->setLayout(keyLayout);
mainLayout->addWidget(lb_show);
mainLayout->addWidget(keyWidget);
this->setLayout(mainLayout);
// clickedWithText
connect(btn_A,SIGNAL(clickedWithText(QString)),
this,SLOT(onClicked(QString)));
connect(btn_B,SIGNAL(clickedWithText(QString)),
this,SLOT(onClicked(QString)));
connect(btn_C,SIGNAL(clickedWithText(QString)),
this,SLOT(onClicked(QString)));
}
void MyWindow::onClicked(QString text)
{
QString str_show = lb_show->text();
str_show += text;
lb_show->setText(str_show);
}
void MyWindow::onAClicked()
{
QString str_show = lb_show->text();
str_show += "A";
lb_show->setText(str_show);
}
void MyWindow::onBClicked()
{
QString str_show = lb_show->text();
str_show += "B";
lb_show->setText(str_show);
}
void MyWindow::onCClicked()
{
QString str_show = lb_show->text();
str_show += "C";
lb_show->setText(str_show);
}#include <QApplication>
#include "MyWindow.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
MyWindow mw;
mw.show();
app.exec();
return 0;
}