我是pyQt的新手,对布局和小部件的工作方式有些困惑。我的理解是我需要创建一个新的小部件,然后在这个小部件中添加一个布局(例如GridLayout),然后将这个布局设置到主窗口上。以下是没有按照我的希望工作,我不知道从哪里开始:
self.grid_widget = QtGui.QWidget(self)
self.grid_widget.setGeometry(120,10,500,235)
gridPalette = self.grid_widget.palette()
gridPalette.setColor(self.grid_widget.backgroundRole(), QtGui.QColor('white'))
self.grid_widget.setPalette(gridPalette)
grid = QtGui.QGridLayout()
self.grid_widget.setLayout(grid)
self.setLayout(self.grid_widget)
我基本上需要将窗口小部件放在某个位置(我设置了几何体)。我可以将网格添加到窗口,但网格覆盖整个窗口,而不是我希望它放置的位置。
如果有人能为此解释管道非常方便!
答案 0 :(得分:0)
答案 1 :(得分:0)
在PyQT中,您通常以“主窗口”开头。为此,我通常会为QtGui.QMainWindow
创建一个子类。从该类实例化的对象是我的“主窗口”。
接下来,我创建一个QtGui.QWidget
的子类。我从该类中创建一个对象,将其称为“主窗口小部件”,并将其置于“主窗口”的中心位置。为该“主窗口小部件”分配布局,您可以开始向其添加子窗口小部件。布局确保子窗口小部件完全对齐。
所以它有点像这样:
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
class CustomMainWindow(QtGui.QMainWindow):
def __init__(self):
super(CustomMainWindow, self).__init__()
self.setGeometry(300, 300, 800, 800)
self.setWindowTitle("my first window")
self.mainWidget = CustomMainWidget(self)
self.setCentralWidget(self.mainWidget)
...
self.show()
''' End Class '''
class CustomMainWidget(QtGui.QWidget):
def __init__(self, parent):
super(CustomMainWidget, self).__init__(parent)
self.mainLayout = None
self.initLayout()
self.putSomeWidgetInTheLayout()
...
def initLayout(self):
# When you use a layout, you do not need to pass a parent when
# constructing the child widgets. The layout will automatically
# reparent the widgets (using QWidget::setParent()) so that they
# are children of the widget on which the layout is installed.
# Widgets can only have other widgets as parent, not layouts.
self.mainLayout = QtGui.QGridLayout()
self.setLayout(self.mainLayout)
def putSomeWidgetInTheLayout(self):
# Notice that I don't assign a parent to 'lbl1'!
lbl1 = QtGui.QLabel("My label")
setCustomSize(lbl1, 160, 40)
self.mainLayout.addWidget(lbl1, *(0,0))
# -> I just added the label widget to the layout
# of the main (central) widget. The label widget
# had no parent widget to begin with. But by adding
# it to the layout, the layout will 'reparent' the
# label widget. So from now on, the label widget is
# a child of the 'main (central) widget'.
lbl2 = QtGui.QLabel("My second label")
setCustomSize(lbl2, 160, 40)
self.mainLayout.addWidget(lbl2, *(0,1))
''' End Class '''
def setCustomSize(x, width, height):
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(x.sizePolicy().hasHeightForWidth())
x.setSizePolicy(sizePolicy)
x.setMinimumSize(QtCore.QSize(width, height))
x.setMaximumSize(QtCore.QSize(width, height))
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
myWindow = CustomMainWindow()
sys.exit(app.exec_())
我希望这很有帮助。 如果您还有任何问题,我很乐意帮助您。