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:
------------)