qt学习之对个人画板的实现(1)

来源:互联网 发布:bilibili直播姬 mac 编辑:程序博客网 时间:2024/05/20 02:54
首先我们尝试一下在一个窗口中添加3个按钮
开始我们在QT下新建一个项目

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include<QPushButton>
#include <QWidget>
class MyWidget : public QWidget
{
    Q_OBJECT
private:
public:
    explicit MyWidget(QWidget *parent = 0);
signals:
public slots:
    void pb1_clicked();
};
#endif // MYWIDGET_H
其中的 explicit 后的是构造函数

signals为信号 slots 后的是槽

#include"mywidget.h"
#include<QApplication>
int main(int argc,char *argv[]){
    QApplication a(argc, argv);
    MyWidget w;//窗体
    w.show();//显示窗体
    return a.exec();
}
接下来谈谈如何加入按钮
从中我们可以看到这里使用了三个一样用法的指针,使用完之后自然要加析构函数。提醒:指针的使用:1.new动态分配内存返回的值必须是指针型;2.传递参数减少内存量的使用使用指针或引用(在Qt编程常用指针作为对象的传递)3.多态时使用(不扯了)
并且在将其中的pb等写入类的成员中,于是代码改为
#include "mywidget.h"
#include<QPushButton>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
//define three buttons
QPushButton *pb1=new QPushButton("button1",this);
//'this' show that connect the button with MyWidget
QPushButton *pb2=new QPushButton("button2",this);
QPushButton *pb3=new QPushButton("button3",this);
pb1->setGeometry(10,10,100,20);
pb2->setGeometry(30,50,100,30);
pb3->setGeometry(440,50,100,30);
//set the positions of these buttons in the Window and their lenth\width
}
MyWidget::~MyWidget(){
delete pb1;
delete pb2;
delete pb3;
}
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include<QPushButton>
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
private:
QPushButton *pb1;
QPushButton *pb2;
QPushButton *pb3;
public:
explicit MyWidget(QWidget *parent = 0);//constructor
~MyWidget();//destructor
signals:
public slots:
};
#endif // MYWIDGET_H
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
这样一来,我们实现了在窗口上显示3个按钮,接下来初步尝试信号与槽机制去完成点击bp1按钮使之弹出窗口。我们要做到的就是处理好有什么信号,以及该信好需
要哪个槽来接受,并作出何种反应。
#include "mywidget.h"
#include<QPushButton>
#include<QMessageBox>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
//define three buttons
pb1=new QPushButton("button1",this);
//'this' show that connect the button with MyWid
pb2=new QPushButton("button2",this);
pb3=new QPushButton("button3",this);
pb1->setGeometry(10,10,100,20);
pb2->setGeometry(30,50,100,30);
pb3->setGeometry(440,50,100,30);
connect(pb1,SIGNAL(clicked()),this,SLOT(pb1_clicked()));//信号的发送者是pb1,而后是表示信号是clicked()
//,this代表信号接收者,之后代表信号接收者处理信号的槽
}
MyWidget::~MyWidget(){
delete pb1;
delete pb2;
delete pb3;
}
void MyWidget::pb1_clicked(){
QMessageBox::information(this,"message","button1 cliked!", QMessageBox::Yes, QMessageBox::No);//按下pb1弹出消息
}

对于头文件中的槽的部分加上
signals:
public slots:
    void pb1_clicked();
};
表明点击pb1时即可弹出对话框。其他大家可以试一试。新手最好是手写,少用Designer,这样有助于熟悉其中的机制。算是初步体验一下qtgui编程。



0 0
原创粉丝点击