Issue with Dynamically Created Widgets



  • I've declared a member array to store the pointers for a bunch of Qt Control widgets (QLineEdit),

    In the main code, I programmatically create these widgets and assign, however they are only accessible while the function is in scope:

    // MyGui.h
    class myGui : public QMainWindow, private Ui::uiFormWin
    {
        Q_OBJECT
        public:
            MyGui(QMainWindow *parent = 0);
            Test();
        private:
            QTimer *pUiTimer;
            QLineEdit* le2T[ 32 ];        
        public slots:       
            void GuiUpdate(void);
    }
    
    // MyGui.c
    MyGui::MyGui(QMainWindow *parent) : QMainWindow(parent)  
    {
        // Create Objects and Assign
        for ( int i = 0 ; i < 32; i++ ){
            le2T[ i ] = new QLineEdit (this);    
        }
    
        // This Displays fine:
        le2T [ 0 ]->setText ("Hello"); 
    
        // Setup Timer To Update Line Edit Later
        pUiTimer = new QTimer(this);
        pUiTimer->setInterval(100);
        connect(pUiTimer, SIGNAL(timeout()), this, SLOT(GuiUpdate()) );
    }
    
    void MyGui::GuiUpdate( void )
    {   
        // This next line causes Run-Time Crash  -- le2T[0] object is null!
        le2T [ 0 ]->setText ("World");  // Error
    }
    

    Interestingly, even though they are no longer accessible, they still appear on the GUI.

    I've tried making these QLineEdit objects as members variables in my class (instead of an array of pointers), but, accessing QLineEdit's member functions fails.. and Qt doesn't even auto-detect these as QLineEdit objects!

        .h
            QLineEdit le2T[ 32 ];   
        .cpp
            le2T[ 0 ].setText ("World");  //  Error
    

    How can I create an array of widgets at run-time, and save as member variables so that they can be accessed from any method in the class?


  • Qt Champions 2016

    Hello,
    In general there is no problem to create widgets on the stack, or in the heap. It should work either way.

    One thing that catches my eye is that you're not initializing your form (not calling setupUi), although this shouldn't be a problem. Otherwise your code looks correct. I still don't see how you start you timer, maybe you could provide some more code, so we are able to provide further assistance?

    One additional thing to check:
    Are you sure that the array le2T is NULL, and not the this pointer? You might be trying to dereference a null this, that'd lead to the crash. Try stopping the debugger just after entering GuiUpdate before actually modifying the line edit array and make sure that you have an object you're operating on.

    Kind regards.



  • @snoop911
    I suspect that you have a race condition.
    Try moving the connect out of the constructor and see if that helps.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.