QObject



  • Hello i have access through an object in this way:

    @
    for (int i =0; i<ui->tableWidget->rowCount();i++)
    {
    QWidget *cbox;
    QString nome_combo, nome_classe;
    cbox = new QWidget;
    cbox = ui->tableWidget->cellWidget(i,4);
    nome_combo = cbox->objectName();
    nome_classe = cbox->metaObject()->className(); \is qcombobox
    nomecl = nome_classe.toStdString();
    if (cbox->inherits(nomecl.c_str()))
    {
    here i need to use the function currentIndex() of the object, but how i can do it?
    }
    }
    @

    Thanks

    Luca

    EDIT: please use @-tags for code highlighting, Gerolf



  • @for (int i =0; i<ui->tableWidget->rowCount();i++)
    {
    QComboBox cbox = qobject_cast<QComboBox>(ui->tableWidget->cellWidget(i,4));
    if (cbox)
    {
    int index = cbox->currentIndex();
    }
    }@



  • Hi luca72,

    first of all, you are creating new objects with
    @
    cbox = new QWidget;
    @
    and then overwrite the pointer with

    @
    cbox = ui->tableWidget->cellWidget(i,4);
    @

    so you create a memory leak. in your if statement, you have to cast.
    This is mostly basic C++ knowledge, which is needed to learn Qt.

    @
    QComboBox* cbobox = qobject_cast<QComboBox*>(cbox);
    @

    to shorten your code, you could do:

    @
    for (int i =0; i<ui->tableWidget->rowCount();i++)
    {
    QWidget cbox = ui->tableWidget->cellWidget(i,4);
    if(0 != cbox)
    {
    QComboBox
    cbobox = qobject_cast<QComboBox*>(cbox);
    if (0 != cbobox)
    {
    cbobox->currentIndex();
    //here i need to use the function currentIndex() of the object, but how i can do it?
    }
    }
    }
    @



  • Just a remark on Gerolf's suggestion:

    [quote author="Gerolf" date="1297092312"]to shorten your code, you could do:
    @
    for (int i =0; i<ui->tableWidget->rowCount();i++)
    {
    QWidget cbox = ui->tableWidget->cellWidget(i,4);
    if(0 != cbox)
    {
    QComboBox
    cbobox = qobject_cast<QComboBox*>(cbox);
    if (0 != cbobox)
    {
    cbobox->currentIndex();
    //here i need to use the function currentIndex() of the object, but how i can do it?
    }
    }
    }
    @[/quote]

    You're checking three times for null here (qobject_cast does it as well). It's not necessary and only clutters your code. The code can be even shorter as I suggested.


Log in to reply
 

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