Search code examples
pythonpyqtqcomboboxqpushbuttonqlineedit

PyQt lineEdit on textEdited signal value lost after function call


#^^^^class stuff here for setting UI^^^^


# connecting combobox to slot/function get_baffle_number
   self.baffle_number_combobox.currentIndexChanged.connect(get_baffle_number)

# connecting PushButton action "clicked" to function on_click
   self.pushButton.clicked.connect(on_click)


#connecting lineEdit to slot/function get_baffle_cost
   self.baffle_cost_lineEdit.textEdited.connect(get_baffle_cost)


@pyqtSlot()
def get_baffle_cost(text):
    baffle_cost = text
    return baffle_cost


def get_baffle_number(text):
    #add 1 to the index returned by comboBox to get the number desired by user
    baffle_number = text + 1
    return baffle_number


def calc_baffle_cost():
    test_total = (get_baffle_cost() * get_baffle_number())
    return test_total


@pyqtSlot()
def on_click(self):
    baffle_cost = calc_baffle_cost()
    print(baffle_cost)

After I connect that lineEdit to the function via the pyqtSlot(), it seems to get the value, but immediately dumps it if I attempt to use baffle_cost from another function. I watch it in PyCharm during debugging and it holds it just as long as the lineEdit has focus it seems. Pressing the pushButton is right when it loses its value.

I cannot use the returned baffle_cost anywhere from get_baffle_cost.

Am I missing something? The furthest I've got is that attempting to simply print calc_baffle_cost() and a hexadecimal is printed. I am assuming that is a memory location, but can't be sure. (new to Python)

Sorry if this isn't enough information. I am simply attempting to take baffle_cost from a lineEdit and multiplying that by a value taken from a comboBox.


Solution

  • It seems my problem was two-fold, or more.

    I was not correctly scoping my functions and not utilizing the right namespaces. (Sorry if this terminology is incorrect. I am new to Python and PyQt.)

    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
    
        # sizing of widgets
    
        def retranslateUi(self, MainWindow):
    
        # UI stuff here QlineEdits, etc.
        self.baffle_cost_lineEdit.editingFinished.connect(self.get_baffle_cost)
    
        def get_baffle_cost(self):
            baffle_cost = self.baffle_cost_lineEdit.text()
            return baffle_cost
    

    This needed to be in the same scope(indentation) as my retranslateUi() function in my Ui_MainWindow Class like above.

    I think if I had better structured my project this wouldn't have been an issue. I have definitely learned my lesson about having it all in one script. (program.py)

    The other issue(s) I encountered is that the PyQt function text() called from a QlineEdit returns a QString and not a str. I simply needed to cast it to a string.

    I was losing the value because the function get_baffle_cost wasn't properly scoped with the baffle_cost_lineEdit