2

我有一些代码在窗口中显示一些小部件。但是,这些小部件不会出现在窗口上:

#!/usr/bin/python
import sys
from PySide import QtGui

class Window(QtGui.QMainWindow):
  def __init__(self):
    super(Window,self).__init__()
    self.initUI()
  def initUI(self):
    self.setGeometry(200,500,400,400)
    self.setWindowTitle("A Grid Layout")
    l1 = QtGui.QLabel("Label 1")
    l2 = QtGui.QLabel("Label 2")
    l3 = QtGui.QLabel("Label 3")
    le1 = QtGui.QLineEdit()
    grid = QtGui.QGridLayout()
    grid.setSpacing(10)
    grid.addWidget(l1,1,0)#widget,row,column
    grid.addWidget(l2,2,1)
    grid.addWidget(l3,3,2)
    grid.addWidget(le1,4,0,1,2)#row,column span
    self.setLayout(grid)#sets layout
    self.show()

def main():
  app = QtGui.QApplication(sys.argv)
  win = Window()
  exit(app.exec_())

if __name__ == "__main__":
  main()

我是 PySide 布局的新手,因此非常感谢任何帮助。

4

1 回答 1

7

AQMainWindow不应该与布局一起使用,而是与包含其内容的中央小部件一起使用。试试这个:

#!/usr/bin/python
import sys
from PySide import QtGui

class Window(QtGui.QMainWindow):
  def __init__(self):
    super(Window,self).__init__()
    self.initUI()
  def initUI(self):
    self.setGeometry(200,500,400,400)
    self.setWindowTitle("A Grid Layout")
    l1 = QtGui.QLabel("Label 1")
    l2 = QtGui.QLabel("Label 2")
    l3 = QtGui.QLabel("Label 3")
    le1 = QtGui.QLineEdit()
    grid = QtGui.QGridLayout()
    grid.setSpacing(10)
    grid.addWidget(l1,1,0)#widget,row,column
    grid.addWidget(l2,2,1)
    grid.addWidget(l3,3,2)
    grid.addWidget(le1,4,0,1,2)#row,column span

    centralWidget = QtGui.QWidget()
    centralWidget.setLayout(grid)
    self.setCentralWidget(centralWidget)

    self.show()

def main():
  app = QtGui.QApplication(sys.argv)
  win = Window()
  exit(app.exec_())

if __name__ == "__main__":
  main()
于 2014-03-15T16:02:00.963 回答