multiple classes in PyQt4

2019-06-28 06:28发布

After learning the Python basics I'm now trying myself in GUI using PyQt4. Unfortunately I'm now stuck figuring out how to use multiple classes and after spending a lot of time trying to get the answer online and not really finding the right answer I hope you can now help me.

So this is my example code:

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.b1 = QtGui.QPushButton("Button", self)
        self.b1.move(100,100)


        self.setGeometry(300,300,200,200)
        self.setWindowTitle("Example")
        self.show()

class Bar(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.initUI()

    def initUI(self):

        self.statusBar().showMessage("Statusbar")


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

Right now only the Button from the "Example" class shows up but not the statusBar from the "Bar" class. So how exactly can I use both classes simultaneously? Does one have to inherit something from the other? Sorry if this might be very clumsy and have a lot of mistakes but thanks if you can help me!

2条回答
爷、活的狠高调
2楼-- · 2019-06-28 07:00

A QMainWindow has QWidgets and one QStatusBar, a QWidget has no QStatusBar. You need to fix your inheritance tree.

import sys
from PyQt4 import QtCore, QtGui

class Example(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        self.statusBar().showMessage("howdy stackoverflowers!!")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())
查看更多
别忘想泡老子
3楼-- · 2019-06-28 07:03

You need to instantiate a Bar object, and call its show method:

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    bar = Bar()
    bar.show()
    sys.exit(app.exec_())

If you want the button and status bar in one window, put all the widgets in the QMainWindow:

import sys
from PyQt4 import QtGui, QtCore

class Bar(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,200,200)
        self.b1 = QtGui.QPushButton("Button", self)
        self.b1.move(100,100)
        self.setWindowTitle("Example")
        self.statusBar().showMessage("Statusbar")

def main():
    app = QtGui.QApplication(sys.argv)
    bar = Bar()
    bar.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
查看更多
登录 后发表回答