初学Qt之---实现对基本组件的动态增删

      再次申明,由于本人初次接触C++和Qt,很多地方不是很熟悉,错误之处在所在所难免,给出的代码仅有参考交流价值。

      实现功能:

      通过“addButton"按钮来增加组件,通过"delButton"按钮来删除组件。

      代码如下:

    

/********MainFrame.h************/

#ifndef MAINFRAME_H_
#define MAINFRAME_H_

#include <QtGui/QWidget>
#include <QtGui/QPushButton>

class MainFrame : public QWidget
{
  Q_OBJECT
  public:
  MainFrame();
  ~MainFrame();
  QWidget *widget;
  public slots:
  void addButton();
  void delButton();
};

#endif

/**********MainFrame.cpp***********/

#include "MainFrame.h"
#include <iostream>

MainFrame::MainFrame()
{
  widget=NULL;
  setGeometry(0,0,500,300);
  QPushButton *button_add=new QPushButton("addButton",this);
  QPushButton *button_del=new QPushButton("delButton",this);
  button_add->setGeometry(20,20,200,50);
  button_del->setGeometry(240,20,200,50);
  connect(button_add,SIGNAL(clicked()),this,SLOT(addButton()));
  connect(button_del,SIGNAL(clicked()),this,SLOT(delButton()));
}

MainFrame::~MainFrame()
{
}

void MainFrame::addButton()
{
   std::cout<<"addButton clicked!"<<std::endl;
   if(widget!=NULL){
     widget->hide();
     widget=NULL;
   }
   widget=new QWidget(this);
   widget->setGeometry(0,120,300,200);
   QPushButton *button1=new QPushButton("AAAAAAAAAA",widget);
   QPushButton *button2=new QPushButton("BBBBBBBBBB",widget);
   button1->setGeometry(20,0,200,50);
   button2->setGeometry(20,100,200,50);
   widget->show();
}

void MainFrame::delButton()
{
   std::cout<<"delButton clicked!"<<std::endl;
   if(widget!=NULL){
     widget->hide();
     widget=NULL;
   }
}



/**********Main.cpp***********/

#include <QtGui/QApplication>
#include "MainFrame.h"

int main(int argc,char *argv[])
{
   QApplication a(argc,argv);
   MainFrame *my=new MainFrame();
   my->show();
   return a.exec();
}


运行截图:

点击"addButton"之后:

点击delButton之后:

(------------完------------)

你可能感兴趣的:(qt)