Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

python - PyQt Main Window vs. Dialog

Probably a silly noob question, but here it is (condensed example):

I've got some basic code to create a QDialog. in practice this is working well and I have something that creates a Pyqtgraph window, loads and plots data, etc:

import sys
from PyQt4 import QtGui

#class Window(QtGui.QMainWindow):
class Window(QtGui.QDialog):

    def __init__(self):
        super(Window, self).__init__()

        # Button to load data
        self.LoadButton = QtGui.QPushButton('Load Data')
        # Button connected to `plot` method
        self.PlotButton = QtGui.QPushButton('Plot')

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.LoadButton)
        layout.addWidget(self.PlotButton)

        self.setLayout(layout)

        self.setGeometry(100,100,500,300)
        self.setWindowTitle("UI Testing")


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

However I would like to create this as a QMainWindow (simply to get maximise, close, etc buttons for now) but if I change the class definition to:

class Window(QtGui.QMainWindow):

I get a blank main window when I run the code. So the simple question is, what do I need to do to make the layout display as it did in QDialog in a QMainWindow?

Best Regards,

Ben

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the doc:

Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.

so the central widget should be created and set up:

    def __init__(self):
        super(Window, self).__init__()

        # Button to load data
        self.LoadButton = QtGui.QPushButton('Load Data')
        # Button connected to `plot` method
        self.PlotButton = QtGui.QPushButton('Plot')

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.LoadButton)
        layout.addWidget(self.PlotButton)

        # setup the central widget
        centralWidget = QtGui.QWidget(self)
        self.setCentralWidget(centralWidget)
        centralWidget.setLayout(layout)

        self.setGeometry(100,100,500,300)
        self.setWindowTitle("UI Testing")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...