2016-11-26 43 views
2

我有一個名爲guiNext.py的PyQt5 Ui和正在重新構建UI的next.py。如何將功能添加到UI按鈕?這是我所擁有的,當我運行next.py並點擊HELLO按鈕時沒有任何反應。通過導入PyQt5向按鈕添加函數Ui

guiNext.py:

# -*- coding: utf-8 -*- 

# Form implementation generated from reading ui file 'guiNext_001.ui' 
# 
# Created by: PyQt5 UI code generator 5.6 
# 
# WARNING! All changes made in this file will be lost! 

from PyQt5 import QtCore, QtGui, QtWidgets 

class Ui_nextGui(object): 
    def setupUi(self, nextGui): 
     nextGui.setObjectName("nextGui") 
     nextGui.resize(201, 111) 
     nextGui.setMinimumSize(QtCore.QSize(201, 111)) 
     nextGui.setMaximumSize(QtCore.QSize(201, 111)) 
     self.centralwidget = QtWidgets.QWidget(nextGui) 
     self.centralwidget.setObjectName("centralwidget") 
     self.helloBtn = QtWidgets.QPushButton(self.centralwidget) 
     self.helloBtn.setGeometry(QtCore.QRect(10, 10, 181, 91)) 
     self.helloBtn.setObjectName("helloBtn") 
     nextGui.setCentralWidget(self.centralwidget) 

     self.retranslateUi(nextGui) 
     QtCore.QMetaObject.connectSlotsByName(nextGui) 

    def retranslateUi(self, nextGui): 
     _translate = QtCore.QCoreApplication.translate 
     nextGui.setWindowTitle(_translate("nextGui", "MainWindow")) 
     self.helloBtn.setText(_translate("nextGui", "HELLO")) 

,這裏是主文件next.py:

#!usr/bin/env python 
#-*- coding: utf-8 -*- 

from PyQt5 import QtCore, QtGui, QtWidgets 
from guiNext import Ui_nextGui 

class mainProgram(Ui_nextGui): 
    def __init__(self, parent=None): 
     Ui_nextGui.__init__(self) 
     self.setupUi(nextGui) 
     self.helloBtn.clicked.connect(self.hello) 

    def hello(self): 
     print ("HELLO") 

if __name__ == "__main__": 
    import sys 
    app = QtWidgets.QApplication(sys.argv) 
    nextGui = QtWidgets.QMainWindow() 
    ui = Ui_nextGui() 
    ui.setupUi(nextGui) 
    nextGui.show() 
    sys.exit(app.exec_()) 

回答

1

你的程序的結構是不完全正確。 use the ui files created by Qt Designer有幾種方法。多重繼承方法可能是最直觀的。這就是你的代碼應該是這樣的:

from PyQt5 import QtCore, QtGui, QtWidgets 
from guiNext import Ui_nextGui 

class mainProgram(QtWidgets.QMainWindow, Ui_nextGui): 
    def __init__(self, parent=None): 
     super(mainProgram, self).__init__(parent) 
     self.setupUi(self) 
     self.helloBtn.clicked.connect(self.hello) 

    def hello(self): 
     print ("HELLO") 

if __name__ == "__main__": 

    import sys 
    app = QtWidgets.QApplication(sys.argv) 
    nextGui = mainProgram() 
    nextGui.show() 
    sys.exit(app.exec_()) 
+0

謝謝。我必須閱讀你鏈接的頁面。很有用。 –