我对包含树 (QTreeView) 的 QWidget 有问题:如果它是单独创建的小部件,我可以显示它,如果它是另一个更高级别小部件的子小部件,我不能这样做。在第二种情况下,我得到的是一个没有树的空小部件。
这有效:
QApplication testApp(argc, argv);
MyTree myTree;
testApp.exec();
这不起作用:
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);
}
这是这两种情况共有的代码(应该没问题):
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;
}