初学Qt之——动态增加组件。

来源:互联网 发布:mac开机按commandr 编辑:程序博客网 时间:2024/05/21 13:22

     实现功能:通过点击按钮来增加几个组件。

     注意事项:刚开始时,我没有使用布局管理器,因此无论怎样点击,增加的组件都不能显示出来。增加布局管理器后,组件正常显示,这说明增加和删除组件需要布局管理器的参与。

     (更正:原来动态增加组建并不一定需要布局管理器的参与,当初测试的时候之所以组件没有显示,那是因为我没有使用show()方法造成的,特此更正。)---(菜鸟作品,错误难以避免,仅有参考价值)

    代码如下:

  

#ifndef MYMAINFRAME_H_#define MYMAINFRAME_H_#include <QtGui/QWidget>#include <QtGui/QLineEdit>#include <QtGui/QPushButton>#include <QtGui/QVBoxLayout>class MyMainFrame : public QWidget{  Q_OBJECT  public:  MyMainFrame();  ~MyMainFrame();  private:  QPushButton *pb1;  QWidget *qw;  QVBoxLayout *qb;  public slots:  void showStation();};  #endif

#include "MyMainFrame.h"#include<iostream> MyMainFrame::MyMainFrame(){  setGeometry(0,0,300,200);  pb1=new QPushButton("click it and list will be shown",this);  std::cout<<"构造方法:"<<this<<"\n";  pb1->setGeometry(20,10,260,40);  qw=new QWidget(this);  qw->setGeometry(40,50,200,90);  qb=new QVBoxLayout(qw);  connect(pb1,SIGNAL(clicked()),this,SLOT(showStation()));}void MyMainFrame::showStation(){    QPushButton *pb2=new QPushButton("first");    qb->addWidget(pb2);    std::cout<<"方法内部:"<<this<<"\n";    QPushButton *pb3=new QPushButton("second");    qb->addWidget(pb3);    pb1->setText("hello");    pb2->setGeometry(0,0,200,30);    pb3->setGeometry(0,0,200,30);    this->update(0,0,300,200);}MyMainFrame::~MyMainFrame(){}

#include <QtGui/QApplication>#include "MyMainFrame.h"int main(int argc,char *argv[]){    QApplication a(argc,argv);    MyMainFrame *my=new MyMainFrame();    my->show();    return a.exec();}

运行截图如下:

点击前:

点击后:

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

原创粉丝点击