Search code examples
pythonpython-3.xpyqtpyqt5qtablewidget

QTableWidget + QPushButton Issue


I am using PyQt5 and I am trying to change the active cell with pushing a button. So I have a QLineEdit for people to type an item in and the button at the moment takes that value and places it in the 0,0 position, like it should. I tried to have the clicked.connect also change the variable that the row number is saved in, but it doesn't seem to be working. Here is my code for my btn_clk:

def btn_clk(self):
    row = 0
    col = 0
    entry = QTableWidgetItem(self.mod_num.text())
    self.form_widget.setCurrentCell(row, col)
    self.form_widget.setItem(row, col, entry)
    row += 1
    self.mod_num.clear()

Of course for the first item I have the 0,0 coord, I get the value that is in the QLineEdit box, I set the current cell, then set the item. This is where I don't know what is going wrong. I have the row variable += 1 to move it down one row in the QTableWidget I have that I set up as 34 total rows.

I know I don't a way to stop it at the moment, but I am more worried about it not changing my cell position at the moment. Any help would be most appreciated.

Update:

To expand on what I am wanting:

example

With the provided example picture what I am trying to do is when someone enters something in the QLineEdit box and presses the Submit button, the method def btn_clk places the text from the QLineEdit into cell 0,0. Then when the user enters a new item into the QLineEdit and presses the Submit button again, it places the text from the QLineEdit into the next row at cell 1,0.

I hope this better explains what I am trying to accomplish.


Solution

  • What happens is that every time you call the btn_clk function you reset the values to row = 0, col = 0.

    What you should do is initialize the variable in __init__:

    def __init__(self, other parameters):
        # some code
        self.row = 0
        self.col = 0
    

    And then in the slot:

    def btn_clk(self):
        entry = QTableWidgetItem({your text})
        self.form_widget.setItem(self.row, self.col, entry)
        self.row += 1
        # another some code