QGraphicsScene, QGraphicsView and QVBoxLayout() problem
Greetings everyone,
Every time I run it seems Qt Creator just stop working, when I commented out the line //mainWindow = new MainWindow();
But if the line is not commented out, MainWindow
will keep appearing many times. Also to check, is the structure of the QGraphicsScene
, QGraphicsView
and QVBoxLayout
correct because I cant seem to make the view to appear when MainWindow is being called in main.cpp.
thanks :)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), keydown_left(false), keydown_right(false),scene(NULL), view(NULL)
{
qDebug("MainWindow");
//mainWindow = new MainWindow();
//qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
scene = new QGraphicsScene(mainWindow);
view = new QGraphicsView(scene, mainWindow);
scene->setSceneRect(-300, 0, 640, 360);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
Egg *egg = new Egg();
QVBoxLayout *layout = new QVBoxLayout();
for (int i = 0; i < ObjCount; ++i) {
FlyingObj *Fo= new FlyingObj();
Fo->setPos(::sin((i * 6.28) / ObjCount) * 500,
::cos((i * 6.28) / ObjCount) * 500);
scene->addItem(Fo);
}
egg->setPos((640-64)/2, 100);//16 - 2*16
scene->addItem(egg);
view->setRenderHint(QPainter::Antialiasing);
view->setBackgroundBrush(QPixmap(":/bg.jpg"));
//view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
view->setDragMode(QGraphicsView::NoDrag);
view->setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Egg game"));
view->resize(640, 360);
QObject::connect(scene, SIGNAL(keyPressEvent(QKeyEvent)), this, SLOT(keyPressEvent(QKeyEvent)));
view->setH开发者_运维技巧orizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setFrameStyle(QFrame::NoFrame);
view->setFocusPolicy(Qt::NoFocus);
view->setCacheMode(QGraphicsView::CacheBackground);
view->showFullScreen();
layout->addWidget(view);
QWidget *w = new QWidget();
w->setLayout(layout);
}
Try to include main function in the project, usually defined separately in a file: Main.cpp, in which it instantiates your MainWindow class:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
Uncommenting mainWindow in the MainWindow constructor is a recursive call, and incorrect way in this context. Lastly, try to change:
layout->addWidget(view);
QWidget *w = new QWidget();
w->setLayout(layout);
into:
setLayout(layout);
精彩评论