PDA

View Full Version : Resizing QML and QMainWindow



hungarycoder
10th January 2011, 12:45
Hi,

I have a qml file which contains a Rectangle Element as the root item. I want this rectangle item to be displayed as the mainwindows central widget and this Rectangle Element should be resized according to the mainwindow. So i did like this,


MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);

QDeclarativeView *view = new QDeclarativeView;
setCentralWidget(view);

QDeclarativeEngine *engine = view->engine();

QDeclarativeComponent component(engine, QUrl::fromLocalFile("qml_files/screen.qml"));
object = component.create();
view->setScene(new QGraphicsScene);
view->scene()->addItem(qobject_cast<QDeclarativeItem*>(object));
}

void MainWindow::resizeEvent(QResizeEvent *)
{
object->setProperty("width", width());
object->setProperty("height", height());
}


screen.qml

Rectangle {
id: window

width: 480; height: 360
color: "#282828"
}

which uses QDeclarativeView, QGraphicsScene, QDeclarativeComponent and QDeclarativeItem, which seems to work. Am i doing it right or a much simpler solution exist

wysota
10th January 2011, 13:05
There is a simpler solution.

view->setResizeMode(QDeclarativeView::SizeRootObjectToVi ew);

hungarycoder
11th January 2011, 05:55
Thanks Wysota,

The solution is amazingly simple.

BobTheProg
19th February 2011, 18:12
With one exception (see below) I carefully copied this example, but the automatic resizing does not work (the rest works 100%). Here is my code:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
QDeclarativeView * pCanvas = new QDeclarativeView;
setCentralWidget(pCanvas);

QDeclarativeEngine *engine = pCanvas->engine();

QDeclarativeComponent component(engine, QUrl::fromLocalFile("test.qml"));
pObject = component.create();
pCanvas->setScene(new QGraphicsScene);
pCanvas->scene()->addItem(qobject_cast<QDeclarativeItem*>(pObject));

pCanvas->scene()->setBackgroundBrush(Qt::yellow);
pCanvas->setResizeMode(QDeclarativeView::SizeRootObjectToVi ew);
}
The part I missed out is the User Interface initialization and setup:

ui(new Ui::MainWindow)
and
ui->setupUi(this);
As a newbie, I cannot see what difference this could make. Any hints gratefully received.