本文介绍了Qt中的错误:QMainWindowLayout :: addItem:请使用公共QMainWindow API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

多次,如代码 layout() - > addWidget(newEdit); 已经工作。
我应该怎么做以防止它?

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

对我的英语很抱歉。

推荐答案

你应该用另一种方式使用布局,因为在你的代码小部件没有aby布局,所以你的指针布局是坏的,所以你的程序崩溃。 Try In constructor例如:

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);

如果你想自己设置窗口部件的位置,那么你根本不需要布局。只要将centralWidget设置为所有其他窗口小部件的父级,并调用setGeometry,没有任何问题。注意,在这种情况下,centralWidget的左上角将具有0; 0子坐标的坐标。

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.

这篇关于Qt中的错误:QMainWindowLayout :: addItem:请使用公共QMainWindow API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 16:04