Search code examples
pythonmatplotlibpyqtpyqt5qcombobox

Is it possible to change a FigureCanvas using Combobox in Python?


How do I switch between already created plots in a GUI using a combobox dropdown menu? Right now my GUI opens, when I click on the combobox nothing happens.

I am fairly new to programming so my knowledge is quite limited. I apologize if the question is too vague.

class Untersuchung(QWidget):  
    def __init__(self): 
        QWidget.__init__(self)
        self.setWindowTitle("Projekt")

        layout = QGridLayout() 
        self.setLayout(layout)

        label1 = QLabel("Choose the Plot") 
        layout.addWidget(label1,0,0)

        self.figure1 = #PLOT1
        self.canvas1 = FigureCanvas(self.figure1)
        self.figure2 = #PLOT2
        self.canvas2 = FigureCanvas(self.figure2)


        self.combobox1 = QComboBox() 
        self.combobox1.addItem("Option1")
        self.combobox1.addItem("Option2")
        layout.addWidget(self.combobox1,1,0)        
        self.combobox1.activated.connect(self.dropdown)

Im not sure what this function should be.

def dropdown(self):     
    if self.combobox1.currentText() == "Option1":
        self.setLayout(layout)
        layout.addWidget(self.canvas1,2,0)
    elif self.combobox1.currentText() == "Option2":
        self.setLayout(layout)
        layout.addWidget(self.canvas2,2,0)

I want the plot that is shown to be replaced in accordance with the chosen combobox option. Any help would be greatly appreciated.


Solution

  • If you want to alternately display widgets in the same window space, it is best to use a QStackedWidget or a QStackLayout, in the following example the first option:

    class Untersuchung(QWidget):
        def __init__(self, parent=None):
            super(Untersuchung, self).__init__(parent)
            self.setWindowTitle("Projekt")
    
            layout = QGridLayout(self)
            label1 = QLabel("Choose the Plot")
            layout.addWidget(label1, 0, 0)
    
            self.figure1 = #PLOT1
            self.canvas1 = FigureCanvas(self.figure1)
            self.figure2 = #PLOT2
            self.canvas2 = FigureCanvas(self.figure2)
    
            self.combobox1 = QComboBox()
            stacked_widget = QStackedWidget()
    
            for text, canvas in zip(
                ("Option1", "Option2"), (self.canvas1, self.canvas2)
            ):
                self.combobox1.addItem(text)
                stacked_widget.addWidget(canvas)
    
            self.combobox1.currentIndexChanged[int].connect(
                stacked_widget.setCurrentIndex
            )
            layout.addWidget(self.combobox1, 1, 0)
            layout.addWidget(stacked_widget, 2, 0)