|
How to use QList class to construct list to contain other components. The following code is based on Qt4.0 SimpleWizard Example,I just make a little modification to let me understand easily. //test.h code #include <QDialog> #include <QList> class QLabel; class QPushButton; class QString; class QVBoxLayout; class QHBoxLayout; class Test:public QDialog { Q_OBJECT public: Test(); void updateLabel(int index); private slots: void nextBtnClicked(); void backBtnClicked(); private: QList<QString> contents; QLabel *label; QPushButton *nextBtn; QPushButton *backBtn; QHBoxLayout *btnLayout; QVBoxLayout *mainLayout; int curIndex; }; //test.cpp code #include "test.h" #include <QList> #include <QPushButton> #include <QLabel> #include <QString> #include <QVBoxLayout> #include <QHBoxLayout> Test::Test() { backBtn=new QPushButton(tr("Back")); nextBtn=new QPushButton(tr("Next")); connect(backBtn,SIGNAL(clicked()),this,SLOT(backBtnClicked())); connect(nextBtn,SIGNAL(clicked()),this,SLOT(nextBtnClicked())); btnLayout=new QHBoxLayout; btnLayout->addStretch(1); btnLayout->addWidget(backBtn); btnLayout->addWidget(nextBtn); label=new QLabel(""); mainLayout=new QVBoxLayout; mainLayout->addWidget(label); mainLayout->addLayout(btnLayout); for(int i=0;i<10;++i) contents.append(QString::number(i)); curIndex=0; updateLabel(curIndex); setLayout(mainLayout); } void Test::updateLabel(int index) { QLabel *newLabel=new QLabel(QString::number(index)); mainLayout->addWidget(newLabel); setWindowTitle(tr("%1 of %2").arg(index).arg(contents.size())); if(index==contents.size()) { nextBtn->setEnabled(false); backBtn->setEnabled(true); } else if(index==0) { nextBtn->setEnabled(true); backBtn->setEnabled(false); } else { nextBtn->setEnabled(true); backBtn->setEnabled(true); } } void Test::backBtnClicked() { if(curIndex>0) { curIndex--; updateLabel(curIndex); } } void Test::nextBtnClicked() { if(curIndex<contents.size()) { curIndex++; updateLabel(curIndex); } }
The above code is very easy,but it also has a bug that I don't know how to control the button's status(enabled or disabled)
|