PDA

View Full Version : Code from main or from QMainWindow differences



qt_developer
20th February 2013, 16:25
Hi all,

I have the next code and works properly:



#include <QApplication>

#include <QMainWindow>
#include <QVBoxLayout>

#include <QTreeView>
#include <QListView>
#include <QTableView>

#include <QStandardItemModel>

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

QMainWindow* mainWindow = new QMainWindow();
QVBoxLayout* verticalLayout = new QVBoxLayout;

QTreeView *tree = new QTreeView();
QListView *list = new QListView();
QTableView *table = new QTableView();

verticalLayout->addWidget(tree);
verticalLayout->addWidget(list);
verticalLayout->addWidget(table);

QWidget* window = new QWidget();
window->setLayout(verticalLayout);
mainWindow->setCentralWidget(window);

QStandardItemModel model( 5, 2 );
for( int r=0; r<5; r++ )
for( int c=0; c<2; c++)
{
QStandardItem *item = new QStandardItem( QString("Row:%0, Column:%1").arg(r).arg(c) );

if( c == 0 )
for( int i=0; i<3; i++ )
{
QStandardItem *child = new QStandardItem( QString("Item %0").arg(i) );
child->setEditable( false );
item->appendRow( child );
}

model.setItem(r, c, item);
}

model.setHorizontalHeaderItem( 0, new QStandardItem( "Foo" ) );
model.setHorizontalHeaderItem( 1, new QStandardItem( "Bar-Baz" ) );

tree->setModel( &model );
list->setModel( &model );
table->setModel( &model );

list->setSelectionModel( tree->selectionModel() );


mainWindow->show();

return app.exec();
}


The problem is when I put the same code inside a QMainWindow, a new window is opened but the widgets: tree, list and table, do not shown any information, they appear empty.

What's wrong?

Best regards.

Added after 10 minutes:

I have changed the line:


QStandardItemModel model( 5, 2 );

by the line:


QStandardItemModel *model = new QStandardItemModel( 5, 2, this );

And now works properly.

amleto
23rd February 2013, 01:48
Do you know why that is?