#include <QApplication>
#include <QtGui>
#include <Qlabel>
class Mywin:public QWidget
{
Q_OBJECT //自定义信号 产生file.moc 文件 file 和文件名相同
private:
QLabel * label1;
QLabel * label2;
QLabel * label3;
QLabel * label4;
QLineEdit *text1;
QLineEdit *text2;
QLineEdit *text4;
QRadioButton *radioButtion;
private slots: //申明槽函数
void my_slot();
public:
Mywin()
{
label1 =new QLabel("数据一:");
label2=new QLabel("数据二:");
label3=new QLabel("运算符:");
label4=new QLabel("结 果:");
text1=new QLineEdit;
text2=new QLineEdit;
text4=new QLineEdit;
QHBoxLayout *hlayout1=new QHBoxLayout;
hlayout1->addWidget(label1);
hlayout1->addWidget(text1);
//text1->setEchoMode(QLineEdit::Password); 设置密码显示
QHBoxLayout *hlayout2=new QHBoxLayout;
hlayout2->addWidget(label2);
hlayout2->addWidget(text2);
QGroupBox * group=new QGroupBox();//("运算符:");
QRadioButton *add=new QRadioButton("+");
QRadioButton *minus=new QRadioButton("-");
QRadioButton *mult=new QRadioButton("*");
QRadioButton *div=new QRadioButton("/");
add->setChecked(true);
QHBoxLayout *radio=new QHBoxLayout;
radio->addWidget(label3);
radio->addWidget(add);
radio->addWidget(minus);
radio->addWidget(mult);
radio->addWidget(div);
//hlayout3->addStretch(1);
group->setLayout(radio);
QHBoxLayout *hlayout3=new QHBoxLayout;
hlayout3->addWidget(label3);
hlayout3->addWidget(group); // 把group 当成普通组件使用
QHBoxLayout *hlayout4=new QHBoxLayout;
hlayout4->addWidget(label4);
hlayout4->addWidget(text4);
QVBoxLayout *vlayout=new QVBoxLayout;
vlayout->addLayout(hlayout1);
vlayout->addLayout(hlayout2);
vlayout->addLayout(hlayout3);
vlayout->addLayout(hlayout4);
this->setLayout(vlayout);
connect(add,SIGNAL(clicked()),this,SLOT(my_slot()));
connect(minus,SIGNAL(clicked()),this,SLOT(my_slot()));
connect(mult,SIGNAL(clicked()),this,SLOT(my_slot()));
connect(div,SIGNAL(clicked()),this,SLOT(my_slot()));
/*
//setWindowTitle("calcutor"); //设置图标
//QIcon icon=QIcon("hao.360.cn.ico");
// setWindowIcon(icon);
//connect(buttonOk,SIGNAL(clicked()),this,SLOT(my_slot()));
// connect(buttonCancle,SIGNAL(clicked()),this,SLOT(my_slot()));
*/
}
};
void Mywin::my_slot()
{
QRadioButton* but=(QRadioButton*)sender();//获取信号源
QString str=but->text(); // 也可直接写 button1 就不用获取信号源
QString str1=text1->text();
QString str2=text2->text();
double num1=str1.toDouble();
double num2=str2.toDouble();
double num3;
if(str=="+")
{
num3=num1+num2;
}
if(str=="-")
{
num3=num1-num2;
}
if(str=="*")
{
num3=num1*num2;
}
if(str=="/")
{
num3=num1/num2;
}
QString str3;
str3.setNum(num3);
text4->setText(str3);
}
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
/*中文编码*/
QTextCodec *code=QTextCodec::codecForName("gbk");
QTextCodec::setCodecForCStrings(code);
Mywin win;
// QWidget win;
win.show();
return app.exec();
}
#include "qt2_calcutor.moc" //为了和自己定义的槽函数调用
信号产生于作用的几点要求:
1,要有发送端 和接收端
2,要包含有 filename.moc 文件
3.一个信号可以对应多个槽函数(用sender() 函数获取信号源 注意类型转换) 反之 也行