简体   繁体   English

Qt:QButtonGroup的QList

[英]Qt: QList of QButtonGroup

Hey! 嘿! I try to do the following 我尝试执行以下操作

    QList<QButtonGroup*> groups;
    for (int i=0; i<nGroup; i++)
    {
        QButtonGroup *objects = new QButtonGroup(this);
        objects->setExclusive(false);
        for (int j=0; j<nObject; j++)
        {
            Led *tempLed = new Led();
            tempLed->setAutoExclusive(false);
            layout->addWidget(tempLed,j,i,Qt::AlignLeft);
            objects->addButton(tempLed);
        }
        groups.append(objects);
    }

And then try to do something like this: 然后尝试执行以下操作:

groups.at(1)->button(2)->setChecked(true);

The code compiles, but at runtime throws unhandled exception. 代码可以编译,但是在运行时会抛出未处理的异常。 What am I doing wrong? 我究竟做错了什么? Any better way to create group of QButtonGroup? 还有更好的方法来创建QButtonGroup组吗?

The QButtonGroup::button function returns the button for a specific ID, but you didn't use an id when you added the button to the buttongroup. QButtonGroup :: button函数返回具有特定ID的按钮,但是在将按钮添加到按钮组时没有使用ID。 QButtonGroup::button returns 0 in your example leading to a null pointer access exception. QButtonGroup :: button在您的示例中返回0,导致空指针访问异常。

...
objects->addButton(tempLed);
...

If you change the code into 如果将代码更改为

...
objects->addButton(tempLed, j );
...

you original code will work. 您的原始代码将起作用。

I prefer QList::at over QList::operator[] because you don't want to change the value (==pointer) in the list. 我更喜欢QList :: at而不是QList :: operator [],因为您不想更改列表中的值(== pointer)。

I think the problem is related with the function at . 我认为这个问题是与功能相关 It returns a const item, and you are calling to a non-const function in it. 它返回一个const项,您正在其中调用一个非const函数。

Use operator[] instead. 请改用operator []

OK, I solved it like this: 好的,我这样解决了:

QButtonGroup *bG;
bG = groups[gr];
QAbstractButton *aB = bG->buttons()[obj];
aB->setChecked(command);

Didn't really get what was the problem thou. 真的没弄清楚问题是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM