简体   繁体   中英

PyQt5 can't create Tabbars or Tabs

I have been struggling to learn PyQt5 (and object oriented programming). In my current script I need to create a tabbed interface but can't seem to manage it. I suspect the problem is related to OOP (I am a novice). "self" seems to be the problem, and I kind of know what that means but not enough to be able to fix it. Below is my latest attempt. It seems like I am using the "wrong self", from elsewhere in the script. I want very much to understand object oriented programming - thanks in advance to anyone kind enough to help!

Some of the code/errors are:

code:

tabbar = QTabBar()  
tab1 = QTabWidget()  
tabbar.addTab(tab1, 'tab1')  

error:

TypeError: arguments did not match any overloaded call:
addTab(self, str): argument 1 has unexpected type 'QTabWidget'
addTab(self, QIcon, str): argument 1 has unexpected type 'QTabWidget'

And here's the code:

class App(QMainWindow):

    def launch(self, filepath):
        subprocess.run(filepath)


    def newLauncher(self, matrix): 
        pass  # cut for brevity


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

        tabbar = QTabBar()
        tab1 = QTabWidget()
        index = tabbar.addTab(tab1, 'tab1')

        self.initUI()


    def initUI(self):

        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

It is good that you want to learn about OOP, but that is not the main problem in this case, but it seems that you do not read the documentation. If we check that it is a QTabBar it would see that it refers to the top part of the QTabWidget , it is that part with buttons.

You do not have to use QTabBar but QTabWidget , QTabWidget has the addTab method that requires as a first parameter the widget that will be displayed on a page, and as a second parameter a title that will appear on the buttons.

Another mistake that I see in your code is that you create the widget but not setting it as part of another widget are just local variables that we know are deleted when the function is finished.

Since you are using QMainWindow you must set QTabWidget as part of a central widget, for this we can use the layouts.

import sys

from PyQt5.QtWidgets import *

class App(QMainWindow):
    def __init__(self):
        super(App, self).__init__()

        centralWidget = QWidget()
        lay = QVBoxLayout(centralWidget)

        tab = QTabWidget()
        lay.addWidget(tab)
        for i in range(5):
            page = QWidget()
            tab.addTab(page, 'tab{}'.format(i))

        self.setCentralWidget(centralWidget)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM