Как к вкладке QTabWidget PyQt5 привязать функцию?
Данный код содержит 2 вкладки: Tab1 и Tab2, а также 2 функции: fun1() и fun2().
Что нужно дописать, чтобы при нажатии на Tab1 выполнилась функция fun1(), а при нажатии Tab2 - fun2()?
main.py
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
import sys
class New(QMainWindow):
def __init__(self):
super(New, self).__init__()
loadUi("tabs1_2.ui", self)
self.tabWidget.currentChanged.connect(self.tabChanged)
@pyqtSlot()
def tabChanged(self):
print('Позиция индекса текущей вкладки:', self.tabWidget.currentIndex())
print('Указатель на страницу:', self.tabWidget.currentWidget())
def fun1(self):
print('Сработала функция 1')
def fun2(self):
print('Сработала функция 2')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = New()
window.showFullScreen()
window.tabChanged()
sys.exit(app.exec_())
tabs1_2.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<widget class="QWidget" name="centralwidget">
<property name="minimumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<widget class="QGroupBox" name="groupBox">
<property name="geometry">
<rect>
<x>30</x>
<y>10</y>
<width>730</width>
<height>570</height>
</rect>
</property>
<property name="title">
<string>GroupBox</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QTabWidget" name="tabWidget">
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(255, 255, 255);</string>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<property name="minimumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<attribute name="title">
<string>Tab 1</string>
</attribute>
</widget>
<widget class="QWidget" name="tab_2">
<property name="maximumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<attribute name="title">
<string>Tab 2</string>
</attribute>
<widget class="QWidget" name="widget_2" native="true">
<property name="geometry">
<rect>
<x>11</x>
<y>11</y>
<width>104</width>
<height>16</height>
</rect>
</property>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
Ответы (2 шт):
Автор решения: Konstantin
→ Ссылка
from PySide2.QtWidgets import *
import sys
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QGridLayout()
self.setLayout(layout)
label1 = QLabel("Индекс вкладки 0.")
label2 = QLabel("Индекс вкладки 1.")
tabwidget = QTabWidget()
tabwidget.blockSignals(True)
tabwidget.currentChanged.connect(self.onChange)
tabwidget.addTab(label1, "Tab 0")
tabwidget.addTab(label2, "Tab 1")
layout.addWidget(tabwidget, 0, 0)
tabwidget.blockSignals(False)
def onChange(self,i):
print(f"Индекс вкладки {i}")
if i == 0:
print("То что должно быть в функции 1")
else:
print("То что должно быть в функции 2")
app = QApplication(sys.argv)
screen = Window()
screen.show()
app.exec_()
Автор решения: S. Nick
→ Ссылка
void QTabWidget::currentChanged(int index)
Этот сигнал излучается всякий раз, когда изменяется индекс текущей страницы. Параметр - это новая позиция индекса текущей страницы или -1.
Примечание: сигнал уведомителя для свойства currentIndex.
main.py
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class New(QMainWindow):
def __init__(self):
super(New, self).__init__()
loadUi("tabs1_2.ui", self)
self.tabWidget.currentChanged.connect(self.tabChanged)
self.tabWidget.setCurrentIndex(0) # +
self.tabChanged(0) # +++
@pyqtSlot(int) # +++ int
def tabChanged(self, index): # +++ index
print('Позиция индекса текущей вкладки:', self.tabWidget.currentIndex())
print('Указатель на страницу:', self.tabWidget.currentWidget())
if index == 0: # +++
self.fun1() # ...
elif index == 1:
self.fun2()
def fun1(self):
print('Сработала функция 1')
def fun2(self):
print('Сработала функция 2')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = New()
# window.showFullScreen()
window.show()
sys.exit(app.exec_())
tabs1_2.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<widget class="QWidget" name="centralwidget">
<property name="minimumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<widget class="QGroupBox" name="groupBox">
<property name="geometry">
<rect>
<x>30</x>
<y>10</y>
<width>730</width>
<height>570</height>
</rect>
</property>
<property name="title">
<string>GroupBox</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QTabWidget" name="tabWidget">
<property name="maximumSize">
<size>
<width>800</width>
<height>600</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(255, 255, 255);</string>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<property name="minimumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<attribute name="title">
<string>Tab 1</string>
</attribute>
</widget>
<widget class="QWidget" name="tab_2">
<property name="maximumSize">
<size>
<width>700</width>
<height>500</height>
</size>
</property>
<attribute name="title">
<string>Tab 2</string>
</attribute>
<widget class="QWidget" name="widget_2" native="true">
<property name="geometry">
<rect>
<x>11</x>
<y>11</y>
<width>104</width>
<height>16</height>
</rect>
</property>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
