我使用两个分割器将窗口分成三个部分,顶部分割器上有三个按钮,我希望每次按下按钮时底部分割器中的布局都会改变,例如当按下添加用户时底部拆分器的布局应该显示一个表单,当按下删除时,它应该显示一个列表等等。
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QtGui.QVBoxLayout(self)
topleft = QtGui.QFrame(self)
topleft.setFrameShape(QtGui.QFrame.StyledPanel)
bottomleft = QtGui.QFrame(self)
bottomleft.setFrameShape(QtGui.QFrame.StyledPanel)
right = QtGui.QFrame(self)
right.setFrameShape(QtGui.QFrame.StyledPanel)
splitterV = QtGui.QSplitter(QtCore.Qt.Vertical)
splitterV.addWidget(topleft)
splitterV.addWidget(bottomleft)
splitterH = QtGui.QSplitter(QtCore.Qt.Horizontal)
splitterH.addWidget(splitterV)
splitterH.addWidget(right)
vbox.addWidget(splitterH)
self.setLayout(vbox)
splitterV.setSizes([100,620])
splitterH.setSizes([960,360])
##Layout for the top left of the splitter
addUserButton = QtGui.QPushButton('Add New User')
addUserButton.clicked.connect(self.addNewUser)
deleteUserButton = QtGui.QPushButton('Delete User')
deleteUserButton.clicked.connect(self.deleteUser)
editUserButton = QtGui.QPushButton('Edit User')
editUserButton.clicked.connect(self.editUser)
topLayout = QtGui.QHBoxLayout()
topLayout.addWidget(addUserButton)
topLayout.addWidget(deleteUserButton)
topLayout.addWidget(editUserButton)
topleft.setLayout(topLayout)
QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
def addNewUser(self):
##Layout for the bottom left of the splitter when button pressed
lbl1 = QtGui.QLabel('First Name')
lbl2 = QtGui.QLabel('Last Name')
fname = QtGui.QLineEdit()
lname = QtGui.QLineEdit()
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addWidget(lbl1, 1, 0)
grid.addWidget(fname, 1, 1)
grid.addWidget(lbl2, 2, 0)
grid.addWidget(lname, 2, 1)
self.bottomleft.setLayout(grid)
def deleteUser(self):
print('Delete')
def editUser(self):
print('Edit')
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
我尝试了很多不同的方法,但仍然无法让任何想法发挥作用?当按下添加用户按钮时,我现在卡住了这个错误:
Traceback (most recent call last):
File "C:\Users\Program\Test\SettingsTab.py", line 81, in addNewUser
self.bottomleft.setLayout(grid)
AttributeError: 'Window' object has no attribute 'bottomleft'
我不知道如何访问窗口的左下方布局并为每次按键更改它,因为如果不是属性,我无法使用self访问它?那是什么?
答案 0 :(得分:2)
实际上initUI
方法导致了问题 - 您还没有将变量定义为类变量,它们是特定于方法的,所以addNewUser
方法无法看到它们。
topleft = QtGui.QFrame(self)
topleft.setFrameShape(QtGui.QFrame.StyledPanel)
bottomleft = QtGui.QFrame(self)
bottomleft.setFrameShape(QtGui.QFrame.StyledPanel)
right = QtGui.QFrame(self)
right.setFrameShape(QtGui.QFrame.StyledPanel)
应为:
self.topleft = QtGui.QFrame(self)
self.topleft.setFrameShape(QtGui.QFrame.StyledPanel)
self.bottomleft = QtGui.QFrame(self)
self.bottomleft.setFrameShape(QtGui.QFrame.StyledPanel)
self.right = QtGui.QFrame(self)
self.right.setFrameShape(QtGui.QFrame.StyledPanel)