本文介绍了PyQt 主窗口与对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个愚蠢的菜鸟问题,但这里是(精简示例):

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

我有一些基本的代码来创建一个 QDialog.在实践中,这运行良好,我有一些东西可以创建 Pyqtgraph 窗口、加载和绘制数据等:

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_())

但是我想将其创建为 QMainWindow(现在只是为了获得最大化、关闭等按钮)但是如果我将类定义更改为:

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):

当我运行代码时,我得到一个空白的主窗口.所以简单的问题是,我需要做什么才能使布局像在 QMainWindow 中的 QDialog 中那样显示?

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?

此致,

推荐答案

来自 doc:

注意:不支持创建没有中央小部件的主窗口.您必须有一个中央小部件,即使它只是一个占位符.

所以应该创建和设置中央小部件:

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")

这篇关于PyQt 主窗口与对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:16