python 按钮未出现在PYQT QVBoxLayout上[重复]

ktca8awb  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(184)

此问题已在此处有答案

PyQt Main Window vs. Dialog(1个答案)
18小时前关闭
我正试图创建一个简单的应用程序,每个功能从主页上的一个按钮访问。
App类如下所示

import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication

class App(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.initUI_M()

    def initUI_M(self):
        self.setWindowTitle("QC Tool")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))

        layout =QtWidgets.QVBoxLayout( )

        button1 =  QtWidgets.QPushButton("GPS")
        button1.clicked.connect(partial(self.plotFlight_map))
        layout.addWidget(button1)

        button2 =  QtWidgets.QPushButton("XY")
        button2.clicked.connect(partial(self.plot_xy))
        layout.addWidget(button2)

        button3 =  QtWidgets.QPushButton("Accel")
        button3.clicked.connect(partial(self.plot_accel))
        layout.addWidget(button3)

        button4 =  QtWidgets.QPushButton("Gyro")
        button4.clicked.connect(partial(self.plot_gyro))
        layout.addWidget(button4)

        button5 =  QtWidgets.QPushButton("Altimeter")
        button5.clicked.connect(partial(self.plot_Altimeter))
        layout.addWidget(button5)

        self._main.setLayout(layout)

        self.center()
        self.show()

这就是我跑步时得到的

我试过设置self._main,或者只设置self作为构造按钮和QVBoxLayout的父项,并且我试过不给按钮分配方法。连接到clicked.connect的所有方法都存在,并且以前连接到一个有效的菜单。
我甚至尝试过不创建小部件对象,而只是将布局添加到self中。
无论我怎么尝试,我都得到完全相同的输出。
我知道这是语法问题,但我找不到...

cbjzeqam

cbjzeqam1#

您忘记设置QMainWindow的主窗口小部件。您已经创建了一个名为“_main”的QWidget对象,但仍需要将其设置为主窗口的中心小部件。
您需要使用QMainWindow的setCentralWidget方法来设置主widget。

def initUI_M(self):
    self.setWindowTitle("QC Tool")
    self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))

    central_widget = QtWidgets.QWidget()  # Add This to your code
    self.setCentralWidget(central_widget) # Add This to your code

    layout = QtWidgets.QVBoxLayout(central_widget)

然后,您需要做的就是添加以下功能:

self.center()
    self.show()
    
    def plotFlight_map(self): # Add This to your code
        print("GPS")
    
    def plot_xy(self): # Add This to your code
        print("XY")
    
    def plot_accel(self): # Add This to your code
        print("Accel")
    
    def plot_gyro(self): # Add This to your code
        print("Gyro")
    
    def plot_Altimeter(self): # Add This to your code
        print("Altimeter")
    
    def center(self): # Add This to your code
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

if __name__ == '__main__': # Add This to your code
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

相关问题