0

QToolBar インスタンスを 1 つだけ持ち、アプリケーションの実行中に何度も変更したいと考えています。しかし、Qt によるメモリ管理が気になります。

次の点を考慮してください。

QToolBar toolBar;
std::cout << toolBar.actions().size() << std::endl; // Prints 0
toolBar.addSeparator(); // will add an action
std::cout << toolBar.actions().size() << std::endl; // Prints 1
toolBar.clear();
std::cout << toolBar.actions().size() << std::endl; // Prints 0 again. Good!

最初、QToolBar のアクションのリストは空です。したがって、最初の cout は「0」を出力します。「addSeparator」によってそのリストに内部アクションが追加されます。したがって、2 番目の cout は "1" を出力します。最後に、予想どおり「クリア」して、すべてのアクションを削除し、最後の cout が再び「0」を出力します。

ここで、「子リスト」で何が起こるかを考えてみましょう:

QToolBar toolBar;
std::cout << toolBar.children().size() << std::endl; // Prints 3. Why?
toolBar.addSeparator(); // will add an action
std::cout << toolBar.children().size() << std::endl; // Prints 5. "addSeparator" has added two children.
toolBar.clear();
std::cout << toolBar.children().size() << std::endl; // Still prints 5. "Clear" did not remove any children!

最初、子リストのサイズは 3 です。次に、"addSeparator" を呼び出すと、2 人の男がそのリストに追加されます。わかりました、私はそれで暮らすことができます。ただし、「クリア」の呼び出し後、これらの人は削除されません。「addSeparator」または「addWidget」呼び出しごとに、2 つの子が追加され、削除されることはありません。

MSVC 2013、WindowsにQt 5.4.1を使用しています。


編集: peppeによって提案されたコードを追加します。ラインコメントを読んでください。

QToolBar toolBar;
std::cout << toolBar.children().size() << std::endl; // Prints 3.
toolBar.addSeparator();
std::cout << toolBar.children().size() << std::endl; // Prints 5. "addSeparator" has added two children.

auto actions = toolBar.actions();

for (auto& a : actions) {
    delete a;
}

std::cout << toolBar.children().size() << std::endl; // Now this prints 4. Shouldn't be 3?
4

1 に答える 1

2

の実装を見てくださいaddSeparator

QAction *QToolBar::addSeparator()
{
    QAction *action = new QAction(this);
    action->setSeparator(true);
    addAction(action);
    return action;
}

これにより、新しい子が作成QActionされ、ウィジェットのアクション リストに追加されます。clearアクション リストをクリアしますが、アクションは破棄しません。したがって、それらは引き続きツールバーの子として存在します。

Qt は、これらのアクションを他の場所で使用していないことを知りません。これらのアクションは、複数のウィジェットで使用することを意図しています。そのメモリを再利用したい場合は、 によって返されたアクションを削除しaddSeparatorます。

于 2016-02-04T15:33:03.970 に答える