PDA

View Full Version : Can we create an array of widgets?



emp1953
30th May 2017, 18:27
I have a gui built from creator/designer. There are MANY Qtextedit boxes on it. I would be nice if these Qtextedit boxes were in an array ( qtextedit(idx) so I could load it within a loop in code rather than explicitly calling out each widget name. Is there such a capability?

d_stranz
31st May 2017, 01:44
You can always create an array of QWidget pointers, but not QWidget instances themselves. This is because QWidget has no public copy constructor or assignment operator.



// You can do this:

QVector< QWidget * > widgetVector;

// but not this:

QVector< QWidget > forbiddenVec;


You can't create such a vector of pointers using Qt Designer; you can only do it in code. You -can- use Qt Designer to lay out your GUI using individual widgets, and then after you call setupUi() in the form's constructor, you can push copies of the pointers (not new widgets) onto a list or vector if it is more convenient to access them by index:




MyWidget::MyWidget( QWidget * parent ) : BaseWidget( parent )
{

ui->setupUi();

widgetVector.push_back( ui->textEdit0 );
widgetVector.push_back( ui->textEdit1 );
// and so on

// later, you can get the nth text edit by
QTextEdit * pNth = widgetVector[ n ];

// which is the same as
QTextEdit * pNth = ui->textEditN;

}

emp1953
17th June 2017, 16:01
That is excellent. Saves alot of code for me.