开发者

How would I create a matrix of check-boxes (without text) in Qt Creator, with dimensions specified at run-time?

Alright, this question is a bit tough. My main window has a section that lets the user specify x and y dimensions, then click a 'generate' button. When this butt开发者_如何学Goon is pressed, a new window will pop up, with a grid (or matrix if you want to call it that) of check-boxes WITHOUT their labels. The grid has the dimensions that the user specified. The user will then select whichever check-boxes they want, and click 'OK', at which point the data will be collected, and the pop-up window will close.

I currently have the window popping up properly, but I have ABSOLUTELY no idea how to create this grid of check-boxes. Perhaps using two 'for' loops? Please provide example code of creating these boxes during run-time.

For those that are curious, this is the first step of a GUI I'm working on that allows the user to generate the domain for a computational fluid dynamics simulation.


you could do it like this:

QVector<QCheckBox*> checkBoxVector;
for(int x = 0; x < 12; ++x){
    for(int y = 0; y < 12; ++y){
        checkBoxVector.append(new QCheckBox(this));
        checkBoxVector.last()->setGeometry(x * 20, y * 20, 20, 20);
    }
}

you want to store the pointers to the newly created items in some container class, so you can use them later (for example to destroy them).

This example is a bit oversimplified. You would have to take care of properly destroying the objects. Using a vector of smart pointers would make this more robust code. Though in this case, since all checkboxes are children of the window or parent widget (the this pointer in my example), they would be destroyed together with the parent. So as long as you just show them once and then destroy the parent, you should be safe.

And of course this way (only one vector) you loose somehow the two dimensions of the grid. If you want to access a single element by it's position, you would have to do a few simple calculations with x and y.

Alternately you could use two vectors, the first one holding the row, which is the second vector, which in turn holds the pointers to the checkboxes. But again this would make the code slightly more complicated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜