Qt for beginners-achieve dynamic addition and deletion of basic components

Source: Internet
Author: User

I again stated that due to my first contact with C ++ and QT, many places are not very familiar, and errors are inevitable. The Code provided only has reference to the exchange value.

Functions:

Use the "addbutton" button to add a component and use the "delbutton" button to delete the component.

The Code is as follows:

/********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();}

Run:

Click "addbutton:

After clicking delbutton:

------------)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.