从QGridLayout删除一行

时间:2012-11-15 20:52:02

标签: c++ qt

全部,我保持QGridLayout QLabels显示多项式的系数。我使用QList<double>代表我的多项式。

每次更新系数时,我都会更新标签。更改列表大小时,我的方法 效果不佳。 QGridLayout::rowCount()无法正确更新。我想知道是否有办法从QGridLayout中删除行。


遵循代码,使用更多(或更少)QGridLayout

更新QLabels尺寸
int count = coefficients->count(); //coefficients is a QList<double> *
if(count != (m_informational->rowCount() - 1)) //m_information is a QGridLayout
{
    SetFitMethod(0);
    for(int i = 0; i < count; ++i)
    {
        QLabel * new_coeff = new QLabel(this);
        new_coeff->setAlignment(Qt::AlignRight);
        m_informational->addWidget(new_coeff, i+1, 0);
        QLabel * param = new QLabel(this);
        param->setAlignment(Qt::AlignLeft);
        param->setText(QString("<b><i>x</i><sup>%2</sup></b>").arg(count-i-1));
        m_informational->addWidget(param, i+1, 1);
        QSpacerItem * space = new QSpacerItem(0,0,QSizePolicy::Expanding);
        m_informational->addItem(space, i+1, 1);
    }

    m_informational->setColumnStretch(0, 3);
    m_informational->setColumnStretch(1, 1);
    m_informational->setColumnStretch(2, 1);
}

SetFitMethod(这是一个初始模型)

void SetFitMethod(int method)
{
    ClearInformational();
    switch(method)
    {
    case 0: //Polynomial fit
        QLabel * title = new QLabel(this);
        title->setText("<b> <u> Coefficients </u> </b>");
        title->setAlignment(Qt::AlignHCenter);
        m_informational->addWidget(title,0,0,1,3, Qt::AlignHCenter);
    }
}

清算方法:

void ClearInformational()
{
    while(m_informational->count())
    {
        QLayoutItem * cur_item = m_informational->takeAt(0);
        if(cur_item->widget())
            delete cur_item->widget();
        delete cur_item;
    }
}

3 个答案:

答案 0 :(得分:2)

问题是QGridLayout::rowCount()实际上并没有返回您可以看到的行数,它实际上返回QGridLayout内部为数据行分配的行数(是的,这个不是很明显,也没有记录。)

要解决此问题,您可以删除QGridLayout并重新创建,或者如果您确信列数不会更改,则可以执行以下操作:

int rowCount = m_informational->count()/m_informational->columnCount();

答案 1 :(得分:0)

好吧,我的解决方案是删除QGridLayout

中的ClearInformational

答案 2 :(得分:0)

我通过创建一个QVBoxLayout(用于行)来解决这个问题,在此我添加了QHBoxLayout(用于列)。在QHBoxLayout中,我然后插入我的小部件(在一行中)。通过这种方式,我能够很好地删除行 - 整体行计数正常运行。除此之外,我还有一个插入方法,由于我能够将新行插入特定位置(所有内容都正确重新排序/重新编号)。

示例(仅来自头部):

QVBoxLayout *vBox= new QVBoxLayout(this);

//creating row 1
QHBoxLayout *row1 = new QHBoxLayout();
QPushButton *btn1x1 = new QPushButton("1x1");
QPushButton *btn1x2 = new QPushButton("1x2");
row1->addWidget(btn1x1);
row1->addWidget(btn1x2);
//adding to vBox - here you can use also insertLayout() for insert to specific location
vBox->addlayout(row1); 

//creating row 2
QHBoxLayout *row2 = new QHBoxLayout();
QPushButton *btn2x1 = new QPushButton("2x1");
QPushButton *btn2x2 = new QPushButton("2x2");
row2->addWidget(btn2x1);
row2->addWidget(btn2x2);
//adding to vBox - here you can use also insertLayout() for insert to specific location
vBox->addlayout(row2);
相关问题