0
以下是從Qt應用程序獲取的代碼示例。我想寫下面的「foreach」循環,就像用C++迭代器循環一樣。如何編寫以下「foreach」作爲C++迭代器
DocumentWindow *MdiWindow::activeDocument()
{
return qobject_cast<DocumentWindow*>(workspace->activeWindow());
}
int i=1;
foreach(QWidget *w, workspace->windowList()) // workspace = new QWorkspace();
{
QString text;
if(i<10)
text = tr("&%1 %2").arg(i++).arg(w->windowTitle());
else
text = w->windowTitle();
QAction *action = windowMenu->addAction(text);
action->setCheckable(true);
action->setChecked(w == activeDocument());
connect(action, SIGNAL(triggered()), mapper, SLOT(map())); // mapper = new QSignalMapper(this);
mapper->setMapping(action, w);
}
以下是我的嘗試。它編譯得很好,但只要在正在運行的應用程序中調用此代碼,它就會崩潰。同時我不知道爲什麼。我做對了嗎?
DocumentWindow *MdiWindow::activeDocument()
{
return qobject_cast<DocumentWindow*>(workspace->activeWindow());
}
int i = 1;
for(QWidgetList::iterator it = (workspace->windowList()).begin(); it != (workspace->windowList()).end(); ++it)
{
QString text;
if(i < 10)
text = QString("&%1 %2").arg(i++).arg((*it)->windowTitle());
else
text = (*it)->windowTitle();
QAction *action = windowMenu->addAction(text);
action->setCheckable(true);
action->setChecked((*it) == activeDocument());
connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
mapper->setMapping(action, (*it));
}
答:我沒有意識到workspace-> windowList()按值返回,因此這兩個迭代器都指向容器的不同實例。