How to: controls widget on the form from the class



  • hello gurus,

    i am learning something new with QT. I added a combo box on the Form using the Qt designer
    lets call it combobox1.

    In the main, I have a new class called MainWindow. In this class I need to add text to the combobox. How can I do it?
    @
    #include <QtGui/QApplication>
    #include "mainwindow.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec&#40;&#41;;
    

    }
    @

    --- cpp
    @
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QWidget>
    #include <QtGui>

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {

    ui->comboBox->addItem("1");
    ui->setupUi(this);
    

    }
    @

    Program breaks unexpectedly


  • Moderators

    welcome to devnet

    I have updated your post with code tags. That way it is easier to read. Please have a look to the "forum help. ":http://qt-project.org/wiki/ForumHelp#e3f82045ad0f480d3fb9e0ac2d58fb01

    Concerning your issue you need to give more details on problem. Do you receive an error message? Please post content.

    Also some details on your environment are required (OS, compiler, IDE, etc.).



  • The problem in the code is the order of lines 12 and 13 (in the MainWindow) constructor. The ui->combobox object does not exist yet before your call to ui->setupUi(). That means that your line before the setupUi call will trigger a segfault.



  • @mods - shouldn't this be moved to General and Desktop? This is not a C++ problem...
    @sherif - what Andre said should be the solution



  • [quote author="raaghuu" date="1343578419"]@mods - shouldn't this be moved to General and Desktop? This is not a C++ problem...
    @sherif - what Andre said should be the solution[/quote]
    Good point on the moving... Will move to General and Desktop.



  • Why not use the QtDesigner to add the text? You can setup the combo box items there.
    have fun coding!



  • QtDesigner is easy to use for simple manipulations. Once it becomes complex you have to use code



  • I think there is a healthy mixture to be found. Use designer where you can, and hand-coded UI's where that is needed. The one is not better than the other, they just have different pros and cons. Good thing is: you're free to mix the two styles as needed in your project.


Log in to reply
 

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