QTreeView no show inside QDockWidget
Hi, I want to show are file system using QTreeView on a QDockWidget. Here is my code:
Code:
QFile file(":/default.txt");
TreeModel model(file.readAll());
file.close();
w.setModel(&model);
swatch1->setWidget(&w);
w.setEnabled(true);
addDockWidget(leftarea, swatch1);
swatch1 is of type QDockWidget. The above code is inside a function of MainWindow. The code runs smoothly, and the tree does not show up.
I also tried another way: putting QTreeView into a QLayout, which in turn be put into QDockWidget. This 2nd code also runs smoothly, and the tree does not show up.
This code is copied from a working example on Qt Creator IDE, and I tested working. The only difference is, in the original QTreeView example, the above code is placed inside the main() { ..... } function.
Does anyone has a working example, putting QTreeView into QDockWidget and working? Thanks in advance.
Re: QTreeView no show inside QDockWidget
Code:
w.setModel(&model);
swatch1->setWidget(&w);
w.setEnabled(true);
If this is your actual code, then the QTreeView instance you are creating on the stack will be destroyed as soon as the method exits, and it will be removed from the dock widget.
Re: QTreeView no show inside QDockWidget
Thank you very much! The problem is solved. Indeed, it is a C/C++ scoping problem. I put the declaration of QTreeView into the header file, and it works!!!
Thank you very much.
Re: QTreeView no show inside QDockWidget
Quote:
I put the declaration of QTreeView into the header file, and it works!!!
That's still the wrong way to do it, Qt-wise. You should create the tree view instance on the heap, not the stack:
Code:
w->setModel(&model);
swatch1->setWidget( w );
w->setEnabled(true);
If you need access to the tree widget from outside the methond where you create it, then put the "QTreeView * w;" declaration as a member variable of the class in the header file.