我是Python,QT4和pyqt的新手,我无法使用setCurrentIndex来更改小部件。我确定我没有正确使用它,但这是我的初始代码。首先是pyqt代码:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Thu May 5 17:15:28 2016
# by: PyQt4 UI code generator 4.9.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.stackedWidget = QtGui.QStackedWidget(self.centralWidget)
self.stackedWidget.setGeometry(QtCore.QRect(-41, -41, 451, 311))
self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
self.page = QtGui.QWidget()
self.page.setObjectName(_fromUtf8("page"))
self.label = QtGui.QLabel(self.page)
self.label.setGeometry(QtCore.QRect(180, 70, 50, 16))
self.label.setObjectName(_fromUtf8("label"))
self.pushButton = QtGui.QPushButton(self.page)
self.pushButton.setGeometry(QtCore.QRect(170, 140, 80, 27))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.stackedWidget.addWidget(self.page)
self.page_2 = QtGui.QWidget()
self.page_2.setObjectName(_fromUtf8("page_2"))
self.label_2 = QtGui.QLabel(self.page_2)
self.label_2.setGeometry(QtCore.QRect(200, 90, 50, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.stackedWidget.addWidget(self.page_2)
MainWindow.setCentralWidget(self.centralWidget)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("MainWindow", "Page 1", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Go to 2", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Page 2", None, QtGui.QApplication.UnicodeUTF8))
以下是我正在尝试的代码:
导入系统 来自表格导入*
class MyDialog(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.Change)
def Change(self):
self.stackedWidget.setCurrentIndex(1)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyDialog()
myapp.show()
sys.exit(app.exec_())
当我按下按钮时,我收到错误“'MyDialog'对象没有属性'stackedWidget'。
我确信这对有经验的程序员来说很容易。
答案 0 :(得分:0)
错误消息的含义正是它所说的:MyDialog
没有创建名为self.stackedWidget
的成员变量,但它试图在Change
中访问这样的变量,所以单击按钮时会引发AttributeError。您想要的变量是self.ui
的成员,它是UI_MainWindow
的实例。
解决方案是将方法Change
更改为:
def Change(self):
self.ui.stackedWidget.setCurrentIndex(1)