QTabWidget and switch-case

Viewed 107

I need different defs depending on the selected tab when I cklick the button. I tried to do this, but it does not work. When you current any tab, "kek" is printed.

from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import *
import sys

app = QApplication(sys.argv)
ui = uic.loadUi("example.ui")

def lol():
    print ('lol')

def kek():
    print ('kek')

case = {
    0 : lol,
    1 : kek
}


ui.pushButton.clicked.connect(case.get(ui.tabWidget.currentIndex()))


ui.show()
app.exec()

And this is the used ui:

enter image description here

<?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="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>330</x>
      <y>490</y>
      <width>93</width>
      <height>28</height>
     </rect>
    </property>
    <property name="text">
     <string>PushButton</string>
    </property>
   </widget>
   <widget class="QTabWidget" name="tabWidget">
    <property name="geometry">
     <rect>
      <x>110</x>
      <y>60</y>
      <width>591</width>
      <height>381</height>
     </rect>
    </property>
    <property name="currentIndex">
     <number>1</number>
    </property>
    <widget class="QWidget" name="tab">
     <attribute name="title">
      <string>Tab 1</string>
     </attribute>
    </widget>
    <widget class="QWidget" name="tab_2">
     <attribute name="title">
      <string>Tab 2</string>
     </attribute>
    </widget>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
1 Answers

The problem is that case.get(ui.tabWidget.currentIndex()) is evaluated at the time of connection, and not at the time of click, so you have the initial currentIndex.

A possible solution is to use a lambda method:

ui.pushButton.clicked.connect(
    lambda: case.get(ui.tabWidget.currentIndex(), lambda: None)()
)

Or create an intermediate function:

def on_clicked():
    case.get(ui.tabWidget.currentIndex(), lambda: None)()

ui.pushButton.clicked.connect(on_clicked)
Related