2

I stumbled upon this in the documentation for QMainWindow::setMenuBar(QMenuBar * menuBar):

Note: QMainWindow takes ownership of the menuBar pointer and deletes it at the appropriate time.

Example code (in a method of a class deriving from QMainWindow):

QMenuBar * menuBar = new QMenuBar(this);
setMenuBar(menuBar) // <-- immediately transfer ownership
// use menuBar pointer to add actions, menus, and what not

Can I still rely on my local pointer to my QMenuBar after a call to setMenuBar? I mean, is it completely guaranteed?

When I delete my QMainWindow derived class, the QMenuBar object is also deleted because the QMainWindow is set as its parent when constructing it - but what policy lies in the later "ownership takeover" through setMenuBar other than a copy of reference/pointer?

4

1 回答 1

1

是的,只要获得所有权的对象还活着,就可以安全地使用该指针。

“拥有”菜单的事实QMainWindow意味着它会在不再需要时将其删除。这在 Qt 中很常见,请参阅Object Trees & Ownership文档。

话虽如此,您的示例代码可以这样重写:

QMenuBar *menu = menuBar();

如有必要,这将创建一个空菜单,因此您不必担心任何所有权转让。只要您需要在 Windows 的菜单栏上执行操作,只需调用该成员函数即可。

于 2013-05-09T14:59:50.720 回答