PDA

View Full Version : Stopped widget in a moveable QGraphicsScene



jano_alex_es
3rd February 2011, 15:54
Hello,

I'm doing a game with items in a QGraphicsScene - QGraphicsView. The scene is the entire level, it's big, so the view is following the main character when it's going outside the boundaries.

But I want to have a static widget (a button) in the bottom-left part of the screen (view). So the view is focusing in the main character but that widget keeps its position on the screen.

I though I could achieve that by calculating (each frame) the QGraphicsView position in the screen and place the button in the proper scene coordinate.

So far I tried with QWidget::pos() and QGraphicsView::sceneRect() but it's no use.

How can I know the position the view is showing of the scene every frame, or, if so, there is any way to have a QGraphicsPixmap item statically in the view?

thanks!

jano_alex_es
4th February 2011, 07:41
So, there is no way to know which part of the QGraphicsScene is showing the QGraphicsView? (sceneRect does not work as expected, it return the whole scene)

Stef
4th February 2011, 08:13
If the button is supposed to be in the bottom-left position of the screen (the qgraphicsview) the whole time, then why don't you just create it on top of the qgraphicsview instead of creating it in the qgraphicsscene?

You can achieve this very easy. Assuming you have a QMainWindow with according ui class and a QGraphicsView widget (graphicsview) is placed in this form. The code look like:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

void createButton(int buttonWidth, int buttonHeight);

private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QPushButton>

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

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::createButton(int buttonWidth, int buttonHeight)
{
QPushButton* button = new QPushButton(ui->graphicsView);
button->setText("Click me!");

button->setGeometry(0,
ui->graphicsView->geometry().height() - buttonHeight,
buttonWidth, buttonHeight);

button->show();
}

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

w.createButton(100,50);

return a.exec();
}

jano_alex_es
4th February 2011, 10:05
Lol, I didn't think in that possibility... thanks!