python Pyqt 控件写成一个类,怎么放进到QMainwindow中?

胡英君
  • 19

coding: utf-8

现在分别是两个窗口,如何把GripLayout2窗口整体嵌入到Mainwindows类中,显示一个界面?

import sys
from PyQt4 import QtGui
from PyQt4.QtGui import *

class Mainwindows(QMainWindow):
    def __init__(self):
        super(Mainwindows, self).__init__()
        self.resize(1024,768)

class GripLayout2(QtGui.QWidget):
    def __init__(self):
        super(GripLayout2, self).__init__()
        self.initUI()
    def initUI(self):
        title = QtGui.QLabel('Title')
        author = QtGui.QLabel('Author')
        review = QtGui.QLabel('Review')
        titleEdit = QtGui.QLineEdit()
        authorEdit = QtGui.QLineEdit()
        reviewEdit = QtGui.QTextEdit()
        grid = QtGui.QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(title, 1, 0)
        grid.addWidget(titleEdit, 1, 1)
        grid.addWidget(author, 2, 0)
        grid.addWidget(authorEdit, 2, 1)
        grid.addWidget(review, 3, 0)
        grid.addWidget(reviewEdit, 3, 1, 5, 1)
        self.setLayout(grid)
        self.setWindowTitle('grid layout')
        self.resize(350, 300)

app = QtGui.QApplication(sys.argv)
ui = Mainwindows()
ui.show()
ex = GripLayout2()
ex.show()
sys.exit(app.exec_())
回复
阅读 4.6k
1 个回答
cosven
  • 186
✓ 已被采纳

思路是:在 QMainWindow 里面创建一个 layout,然后把 GridLayout2 窗口加入 layout 里面(这个思路有点问题,我记错了)

在 PyQt4 里面,QMainWindow 自己本来已经有一个 layout 了,你只需要调用 setCentralWidget 给 QMainWindow 指定一个 widget 就好了。

题外话:建议用 PyQt5 + python3 来做练习。PyQt4 已经过去好久了,5 的资源应该更多一点。

代码如下:

import sys
from PyQt4 import QtGui
from PyQt4.QtGui import *


class GripLayout2(QtGui.QWidget):
    def __init__(self, parent=None):
        super(GripLayout2, self).__init__(parent)
        self.initUI()


    def initUI(self):
        title = QtGui.QLabel('Title')
        author = QtGui.QLabel('Author')
        review = QtGui.QLabel('Review')
        titleEdit = QtGui.QLineEdit()
        authorEdit = QtGui.QLineEdit()
        reviewEdit = QtGui.QTextEdit()
        grid = QtGui.QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(title, 1, 0)
        grid.addWidget(titleEdit, 1, 1)
        grid.addWidget(author, 2, 0)
        grid.addWidget(authorEdit, 2, 1)
        grid.addWidget(review, 3, 0)
        grid.addWidget(reviewEdit, 3, 1, 5, 1)
        self.setLayout(grid)
        self.setWindowTitle('grid layout')
        self.resize(350, 300)


class Mainwindows(QMainWindow):
    def __init__(self):
        super(Mainwindows, self).__init__()
        self.resize(1024,768)

        self.subwidget = GripLayout2(self)
        self.setCentralWidget(self.subwidget)


app = QtGui.QApplication(sys.argv)
ui = Mainwindows()
ui.show()
sys.exit(app.exec_())
        
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏