PDA

View Full Version : QTreeView no show inside QDockWidget



yuping
9th March 2017, 15:13
Hi, I want to show are file system using QTreeView on a QDockWidget. Here is my code:



QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();

QTreeView w;
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.

d_stranz
9th March 2017, 22:35
QTreeView w;
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.

yuping
10th March 2017, 02:59
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.

d_stranz
11th March 2017, 18:05
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:



QTreeView * w = new QTreeView( swatch1 );
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.