-1

我正在尝试QStandardItemModel在 Qt 中使用模型。我已经通过以下两种方式做到了。在第二种方法中,我只是扩展了循环,我得到redefinition of 'item'了错误,而第一种方法工作正常。

  • 方法一

    QStandardItemModel * model = new QStandardItemModel( 3, 1 );
    QStringList modelStepsTags = {"item-1","item-2","item-3"};
    for( int r=0; r<3; r=r+1 )
    {
        QStandardItem *item = new QStandardItem( modelStepsTags.at(r) );
        model->setItem(r, 0, item);
    }
    
  • 方法二

    QStandardItemModel * model = new QStandardItemModel( 3, 1 );
    QStringList modelStepsTags = {"item-1","item-2","item-3"};
    QStandardItem *item = new QStandardItem( modelStepsTags.at(0) );
    model->setItem(0, 0, item);
    QStandardItem *item = new QStandardItem( modelStepsTags.at(1) );
    model->setItem(1, 0, item);
    QStandardItem *item = new QStandardItem( modelStepsTags.at(2) );
    model->setItem(2, 0, item);
    
4

1 回答 1

1

项目被定义了 3 次。

QStandardItemModel * model = new QStandardItemModel( 3, 1 );
QStringList modelStepsTags = {"item-1","item-2","item-3"};
QStandardItem *item = new QStandardItem( modelStepsTags.at(0) ); // here
model->setItem(0, 0, item);
QStandardItem *item = new QStandardItem( modelStepsTags.at(1) ); // here
model->setItem(1, 0, item);
QStandardItem *item = new QStandardItem( modelStepsTags.at(2) ); // and here
model->setItem(2, 0, item);

您可以摆脱重用第一个定义

QStandardItemModel * model = new QStandardItemModel( 3, 1 );
QStringList modelStepsTags = {"item-1","item-2","item-3"};
QStandardItem *item = new QStandardItem( modelStepsTags.at(0) );
model->setItem(0, 0, item);
item = new QStandardItem( modelStepsTags.at(1) ); // reuse
model->setItem(1, 0, item);
item = new QStandardItem( modelStepsTags.at(2) ); // reuse
model->setItem(2, 0, item);

或者完全丢弃变量,因为它是多余的

QStandardItemModel * model = new QStandardItemModel( 3, 1 );
QStringList modelStepsTags = {"item-1","item-2","item-3"};
model->setItem(0, 0, new QStandardItem( modelStepsTags.at(0) ));
model->setItem(1, 0, new QStandardItem( modelStepsTags.at(1) ));
model->setItem(2, 0, new QStandardItem( modelStepsTags.at(2) ));
于 2018-06-14T19:52:13.770 回答