Pregunta

I have a problem with a QWidget that contains a tree (QTreeView): I can display it if it is created as a widget on its own, and I cannot do the same if it is a subwidget of another higher level widget. In this second case, what I get is an empty widget without the tree.

This works:

QApplication testApp(argc, argv);
MyTree myTree;
testApp.exec();

This does not work:

class MainWindow : public QMainWindow
{
    Q_OBJECT

    QSplitter *spl1, *spl2;
    QMdiArea *mdiArea;
    QTableWidget *other;

public:
    MainWindow();
    void LoadTree();
    MyTree *myTree;
};


MainWindow::MainWindow(QWidget *_parent)
    : QMainWindow(_parent), myTree(0)
{
    mdiArea = new QMdiArea;
    other = new QTableWidget;

    spl1 = new QSplitter(Qt::Vertical, this);
    spl1->addWidget(mdiArea);
    spl1->addWidget(other);

    LoadTree();

    spl2 = new QSplitter(Qt::Horizontal, this);
    spl2->addWidget(myTree);
    spl2->addWidget(spl1);

    setCentralWidget(spl2);
}

void MainWindow::LoadTree()
{
    myTree = new MyTree(this);
}

Here is the code common to the two cases (which should be OK):

class MyTree : public QWidget
{
    Q_OBJECT

public:
    explicit MyTree(QWidget *_parent = 0);
    int RefreshTree();

private slots:
    void HandleTreeWidgetEvent(QModelIndex);

private:
    QWidget *parent;
    QTreeView *pjrTree;
    QTreeView *GetNewTree();
};

MyTree::MyTree(QWidget *_parent) :
    QWidget(_parent),
    parent(_parent)
{
    pjrTree = GetNewTree();

    if(pjrTree) {
        if(parent == 0)
            pjrTree->show();
    }
    else {
        // Never gets here
    }
}

QTreeView* MyTree::GetNewTree()
{
    QFileSystemModel *model = new QFileSystemModel;
    model->setReadOnly(true);
    model->setRootPath("/my/path/");

    QTreeView* pjrTree = new QTreeView;
    pjrTree->setModel(model);
    pjrTree->setRootIndex(model->index("/my/path/"));

    QModelIndex index;
    index = model->index(4, 1);     // temp values - no effect

    return pjrTree;
}
¿Fue útil?

Solución 2

Deriving the class MyTree from QTreeView, instead of having a pointer to QTreeView as a member variable, fixed my problem.

Otros consejos

Is the tree view the only widget that does not display? I would suggest passing the splitter it will be contained in as the parent, rather than the main window, when you instantiate the tree.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top