Search code examples
python-3.xpyqt5qcombobox

How to store and pass value from QComboBox without immediate activation of another function?


How to make the application printing 'You clicked the button1 for currency XXX' only after the user pushed the button 'Strategy1', and not when he/she just selected the currency?

Here is what I have done so far, but it prints 'You clicked ...' right after the user selected currency from QComboBox

from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

app = QApplication([])

def button1_clicked(curr_pair):
    alert = QMessageBox()
    alert.setText('You clicked the button1 for currency {}'.format(curr_pair))
    alert.exec_()

button1 = QPushButton('Strategy1')
button1.setToolTip('Click to run strategy 1')
button1.show()
button1.clicked.connect(button1_clicked)

combo = QComboBox()
combo.addItems(['', 'eur', 'usd', 'gbp'])
combo.show()
combo.activated[str].connect(button1_clicked)

window = QWidget()
layout = QVBoxLayout()

title1 = QLabel("Choose currency") 
title1.setAlignment(Qt.AlignCenter) 
title2 = QLabel("Push the button") 
title2.setAlignment(Qt.AlignCenter) 

layout.addWidget(title1)
layout.addWidget(combo)
layout.addWidget(title2)
layout.addWidget(button1)

window.setLayout(layout)
window.show()

app.exec_()

Solution

  • Try it:

    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import Qt
    
    app = QApplication([])
    
    def button1_clicked(curr_pair):
        alert = QMessageBox()
        if curr_pair:
            alert.setText('You clicked the button1 for currency: `{}`'.format(curr_pair))
        else:
            alert.setText('You have pressed the button1 no currency is selected !!!')
        alert.exec_()
    
    currencyName = QLabel("")                                              # <--- +++
    
    button1 = QPushButton('Strategy1')
    button1.setToolTip('Click to run strategy 1') 
    button1.show()
    
    #button1.clicked.connect(button1_clicked)
    button1.clicked.connect(lambda : button1_clicked(currencyName.text())) # <--- +++
    
    combo = QComboBox()
    combo.addItems(['', 'eur', 'usd', 'gbp'])
    combo.show()
    
    #combo.activated[str].connect(button1_clicked)
    combo.activated[str].connect(currencyName.setText)                      # <--- +++
    
    window = QWidget()
    layout = QVBoxLayout()
    
    title1 = QLabel("Choose currency")      
    title1.setAlignment(Qt.AlignCenter) 
    title2 = QLabel("Push the button")      
    title2.setAlignment(Qt.AlignCenter) 
    
    layout.addWidget(title1)
    layout.addWidget(combo)
    layout.addWidget(title2)
    layout.addWidget(button1)
    
    window.setLayout(layout)
    window.show()
    
    app.exec_()
    

    enter image description here