> if __name__=='__main__':app = QApplication(sys.argv)MainWindow = QMainWindow()ui = Ui_MainWindow()ui.setupUi(MainWindow)MainWindow.show()app.exec()
什么也不会显示
如果你不想修改main中的内容,必须在class Ui_MainWindow(QWidget) 类中添加一个初始化方法就可以了:
def __init__(self):super().__init__()self.setupUi(MainWindow)
完整代码如下:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow,QWidgetclass Ui_MainWindow(QWidget):def __init__(self):super().__init__()self.setupUi(MainWindow)def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(800, 600)self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setObjectName("centralwidget")self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)self.verticalLayoutWidget.setGeometry(QtCore.QRect(230, 130, 160, 112))self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)self.verticalLayout.setContentsMargins(0, 0, 0, 0)self.verticalLayout.setObjectName("verticalLayout")self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)self.pushButton.setObjectName("pushButton")self.verticalLayout.addWidget(self.pushButton)self.pushButton_2 = QtWidgets.QPushButton(self.verticalLayoutWidget)self.pushButton_2.setObjectName("pushButton_2")self.verticalLayout.addSpacing(10)# 在按钮1 和 按钮2 之间增加距离10self.verticalLayout.addSpacing(10)self.verticalLayout.addWidget(self.pushButton_2)self.pushButton_3 = QtWidgets.QPushButton(self.verticalLayoutWidget)self.pushButton_3.setObjectName("pushButton_3")self.verticalLayout.addWidget(self.pushButton_3)self.pushButton_4 = QtWidgets.QPushButton(self.verticalLayoutWidget)self.pushButton_4.setObjectName("pushButton_4")self.verticalLayout.addWidget(self.pushButton_4)self.setLayout(self.verticalLayout)MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))self.menubar.setObjectName("menubar")MainWindow.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)# 设置垂直布局间距为10self.verticalLayout.setSpacing(10)self.setLayout(self.verticalLayout)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))self.pushButton.setText(_translate("MainWindow", "1"))self.pushButton_2.setText(_translate("MainWindow", "2"))self.pushButton_3.setText(_translate("MainWindow", "3"))self.pushButton_4.setText(_translate("MainWindow", "4"))if __name__=='__main__':app = QApplication(sys.argv)MainWindow = QMainWindow()ui = Ui_MainWindow()ui.setupUi(MainWindow)MainWindow.show()app.exec()
以上代码运行的效果如下: