2
for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            QLineEdit *newEdit = new QLineEdit(" ");
            newEdit->setGeometry(y * 50, x * 25, 50, 25);
            newEdit->setText("0");
            layout()->addWidget(newEdit);
            objMatrix[y + x * size] = newEdit;
        }
    }

I am using that code to add widgets dynamicly. Then i get this error:

QMainWindowLayout::addItem: Please use the public QMainWindow API instead

As many times, as code layout()->addWidget(newEdit); has worked. What should i do to prevent it?

Sorry for my english.

2 Answers2

3

You should work with layouts in another way because in your code widget has not aby layout, so your pointer to layout is bad, so you programm crashes. Try In constructor for example:

        

QWidget *centralWidget = new QWidget(this);   
QGridLayout *layout = new QGridLayout();
centralWidget->setLayout(layout);
        
layout->addWidget(new QPushButton("Button  1"),0,0);
layout->addWidget(new QPushButton("Button  2"),0,1);     
layout->addWidget(new QPushButton("Button  3"),0,2);     
 
setCentralWidget(centralWidget); 

If you want set position of widgets yourself then you don't need layout at all. Just set centralWidget as parent to all your another widgets and call setGeometry without any issue. Note that in this case top left corner of centralWidget will have 0;0 coordinates for child widgets.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • Is there a layout without auto aligment? I mean, i just want to set X and Y coordinates by myself, not as layout wants. – user3526985 Oct 19 '14 at 20:59
1

You must first add central widget in window. And insert widgets in him.

ExtAsk
  • 51
  • 2
  • I did, but then my program crashes without any errors. (`QWidget *wdg; wdg->layout()->addWidget(newEdit); this->setCentralWidget(wdg);`) – user3526985 Oct 19 '14 at 20:47
  • QWidget *widget = new QWidget(); QVBoxLayout *VBoxLayout = new QVBoxLayout(); widget->setLayout(VBoxLayout); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { QLineEdit *newEdit = new QLineEdit(" "); newEdit->setGeometry(y * 50, x * 25, 50, 25); newEdit->setText("0"); widget->layout()->addWidget(newEdit); objMatrix[y + x * size] = newEdit; } } setCentralWidget(widget); – ExtAsk Oct 19 '14 at 20:56
  • Ty, but then my widgets will be not in their places. http://storage8.static.itmages.ru/i/14/1019/h_1413752703_9967623_0bb6765981.png so i can't place them by X and Y coordinates. – user3526985 Oct 19 '14 at 21:02