QGraphicsScene on a QMainWindow

2.3k views Asked by At

Still new to Python so I'm trying to get a QGraphicsScene to be inside a a QMainWindow. Right now the way I have it coded is that two windows will appear but I only want one window to appear with the QGraphicsScene "inside" the QMainWindow. Here is my code:

import sys
from PyQt4 import QtGui, QtCore

class MyView(QtGui.QGraphicsView):
    def __init__(self):
        QtGui.QGraphicsView.__init__(self)

        self.scene = QtGui.QGraphicsScene(self)
        self.item = QtGui.QGraphicsRectItem(300,400,100,100)
        self.scene.addItem(self.item)
        self.setScene(self.scene)

class Window(QtGui.QMainWindow):
    def __init__(self):
        #This initializes the main window or form
        super(Window,self).__init__()
        self.setGeometry(50,50,900,700)
        self.setWindowTitle("Pre-Alignment system")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    view = MyView()
    view.show()
    sys.exit(app.exec_())

run()

Much thanks!

2

There are 2 answers

2
mdurant On BEST ANSWER

Qt (and other GUI toolkits) believe in parenting. The have one window or widget within another, set its parent. Note that you should be calling show on the outer one.

import sys
from PyQt4 import QtGui, QtCore

class MyView(QtGui.QGraphicsView):
    def __init__(self, parent=None):
        QtGui.QGraphicsView.__init__(self, parent=parent)

        self.scene = QtGui.QGraphicsScene(self)
        self.item = QtGui.QGraphicsRectItem(300,400,100,100)
        self.scene.addItem(self.item)
        self.setScene(self.scene)

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        #This initializes the main window or form
        super(Window,self).__init__(parent=parent)
        self.setGeometry(50,50,900,700)
        self.setWindowTitle("Pre-Alignment system")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    view = MyView(GUI)
    GUI.show()
    sys.exit(app.exec_())

run()
7
Mel On

You have to create your QGraphicsScene inside your QMainWindow (just like you want it to appears)

Then in the main, you only create an instance of Window and show it.

class Window(QtGui.QMainWindow):
    def __init__(self):
        #This initializes the main window or form
        super(Window,self).__init__()
        self.setGeometry(50,50,900,700)
        self.setWindowTitle("Pre-Alignment system")
        #create the view
        self.view=MyView()
        self.setCentralWidget(self.view)

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    GUI.show()
    sys.exit(app.exec_())