PDA

View Full Version : creating a "path" for the menu item



roxton
17th January 2009, 11:44
Hello! I write the code that shows a part of file system as the menu. Subfolders are the submenus, etc. All works fine, but now I need to write a slot for the "filename" menu item selection.
In that slot, I need to determine a sequence of parent titles to make a path for the file.
For example, my menu structure is: Foo - Bar - file.txt
When I click on the file.txt menu item, I need to iterate through the parents to get their titles.
So my code is:


void rvln::test_slot()
{
QAction *a = qobject_cast<QAction *>(sender());
QString path;
path.prepend (a->text());

QMenu *m_parent = qobject_cast<QMenu *> (a->parentWidget());

while (m_parent)
{
path.prepend("/").prepend (m_parent->title());
m_parent = qobject_cast<QMenu *> (m_parent->parentWidget());
}
qDebug() << path;
}

This code have a strange behavior - the nearest (previous) upper level "directory" is dropped out. So I have not Foo/Bar/file.txt, but Foo/file.txt instead.

jpn
17th January 2009, 11:51
You could use QAction::setData() to store the full path in the action. Then you wouldn't have to iterate anything... ;)

roxton
17th January 2009, 12:11
Thank you! :) I'll use it. But why the iteration through the parents works in a such strange way?

jpn
17th January 2009, 12:42
But why the iteration through the parents works in a such strange way?
Hmm, good question. According to my test case it works fine:


// main.cpp
#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc, argv);

QMenu menu("Foo");
QMenu* subMenu = menu.addMenu("Bar");
QAction* action = subMenu->addAction("File");

QString path = action->text();
QMenu *m_parent = qobject_cast<QMenu *> (action->parentWidget());
while (m_parent)
{
path.prepend("/").prepend (m_parent->title());
m_parent = qobject_cast<QMenu *> (m_parent->parentWidget());
}
qDebug() << path; // outputs "Foo/Bar/File" for me
}

Perhaps there's something wrong with the menu hierarchy construction?

wysota
17th January 2009, 16:32
I don't know how the objects are constructed in this particular case, but in general the menu object is not (or at least doesn't have to be) the parent of the QAction object, so there is a possibility items in the deepest menu in the hierarchy are owned by its parent.