PYQT中添加Qframe并设置大小

Adding a Qframe in PYQT and set size

我正在尝试在我的程序 GUI 中间添加一个 QFrame。我尝试了多行代码,但仍然无法显示 :( 这是我尝试过的一个简单实现。有什么帮助吗?

class gameWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,1280,800)
        self.setWindowTitle("Intel")
        self.setWindowIcon(QtGui.QIcon("Intel.png"))
        #self.setStyleSheet("background-color: rgb(255, 255, 255);\n")
                           #"border:1px solid rgb(0, 131, 195);")

        self.centralwidget = QtGui.QWidget(self)
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.resize(300,300)
        self.frame.setStyleSheet("background-color: rgb(200, 255, 255)")

您创建了一个框架,但从未将其添加到任何布局,因此未显示。

QMainWindow 带有带有菜单栏、工具栏、状态栏等的预定义布局 (Qt Doc)。 要显示框架,您只需执行 self.setCentralWidget(self.frame),即可将其插入主 window 布局中。

但很有可能您实际上并不需要所有这些,只需使用 QWidget:

class gameWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300,300,1280,800)

        self.frame = QtGui.QFrame()
        self.frame.resize(300,300)
        self.frame.setStyleSheet("background-color: rgb(200, 255, 255)")

        layout=QtGui.QVBoxLayout()
        layout.addWidget(self.frame)
        self.setLayout(layout)

最后,来自Qt Doc的提醒就一个目的QFrame

The QFrame class is the base class of widgets that can have a frame.
The QFrame class can also be used directly for creating simple placeholder frames without any contents.