[파이썬] PyQt 탭 (`QTabWidget`) 위젯

In this blog post, we will explore how to use the PyQt QTabWidget widget in Python. The QTabWidget provides a tabbed interface, allowing users to switch between different panels or views within an application.

Installation

Before we can start using PyQt and QTabWidget, we need to make sure that we have it installed. You can install PyQt using pip with the following command:

pip install pyqt5

Creating a Basic QTabWidget

To create a basic QTabWidget in PyQt, we first need to import the necessary modules and create a new instance of the QTabWidget class:

from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QWidget

app = QApplication([])
window = QMainWindow()

tab_widget = QTabWidget()
window.setCentralWidget(tab_widget)

In the code snippet above, we import QApplication, QMainWindow, QTabWidget, and QWidget from the PyQt5.QtWidgets module. We then create an instance of the QApplication class and QMainWindow class. Next, we create a QTabWidget instance and set it as the central widget of the main window using the setCentralWidget() method.

Adding Tabs to the QTabWidget

To add tabs to the QTabWidget, we create instances of QWidget as the content of each tab and use the addTab() method to add them to the tab widget:

tab1 = QWidget()
tab2 = QWidget()

tab_widget.addTab(tab1, "Tab 1")
tab_widget.addTab(tab2, "Tab 2")

In the example above, we create two instances of QWidget as the content for each tab. We then use the addTab() method of the QTabWidget to add these tabs, specifying the tab widget and the name for each tab.

Customizing the Tab Appearance

We can also customize the appearance of the tabs by setting properties such as the tab position, tab shape, and tab text alignment. Here’s an example of how to set the tab position to be on the left side:

tab_widget.setTabPosition(QTabWidget.West)

And here’s an example of how to set the tab shape to be rounded:

tab_widget.setTabShape(QTabWidget.Rounded)

Additionally, if you want to change the alignment of the tab text, you can use the setTabTextAlignment() method. By default, the text is aligned to the center. Here’s an example of how to align the text to the left:

tab_widget.setTabTextAlignment(Qt.AlignmentFlag.AlignLeft)

Conclusion

In this blog post, we learned how to use the QTabWidget widget in PyQt to create a tabbed interface in Python. We saw how to create a basic QTabWidget, add tabs to it, and customize its appearance. With the QTabWidget, you can create a versatile UI with multiple panels or views that can be easily switched between by the user.

Stay tuned for more PyQt tutorials and happy coding!