-1

I want to make that when i click on particular cell on the QTableWidget it will block the corresponding rows and I want to return the value of each row selected into the QLineEdit.

Screenshot of the gui

I couldnt seem to find the solution my code only return when i click it will block the rows but not getting the value.

def click_inventorytable(self):
        self.tableInventory.setSelectionBehavior(QtWidgets.QTableView.SelectRows)
        index = (self.tableInventory.selectionModel().currentIndex())
        value = index.row()
        list = [value]
        if(len(list)==6):
            self.lineproductnameinv.setText((list[1]))
            self.linedescinv.setText((list[2]))
            self.combocateinv.setText((list[3]))
            self.linepriceinv.setText((list[4]))
            self.linecurrentstock.setText((list[5]))
            self.addstock.setText('')

  • please provide a [mre] – eyllanesc Apr 13 '21 at 04:31
  • Please avoid putting irrelevant as *Any suggestion and correction will be so much appreciated. Thank you so much!* as they do not help at all (it is just noise). Also read [ask] and review the [tour] – eyllanesc Apr 13 '21 at 04:40
  • On the other hand I have another question, in the QLineEdit it is easy to understand that the text of the corresponding column should be displayed, but in the QComboBox that should be displayed? O Should the qcombobox option shown in the table be selected? – eyllanesc Apr 13 '21 at 04:46
  • Precisely because it is your first question I have given you several comments and links so that you know how to improve your post. If you don't give feedback then it is difficult to help you – eyllanesc Apr 13 '21 at 04:47
  • sorry for my mistake of writing question, this is my very first question here in stackoverflow, i will avoid in the future. – diamondmania Apr 13 '21 at 04:49
  • No, why don't you correct it now? Why is there a need to do it in new posts? – eyllanesc Apr 13 '21 at 04:50
  • yes the text in table for combobox will be shown in the option, i am not very sure if its the correct way using .setText for combo box – diamondmania Apr 13 '21 at 04:52
  • Okay, now work on providing an MRE: [mre] – eyllanesc Apr 13 '21 at 04:53
  • I was going to answer, but frankly I find it really hard, as there are a lot of problems with your code. 1. Setting the selection behavior in a function that *reacts to selections* is not good, especially if doing it only to get the row. 2. `index.row()` returns a row *number*, not its contents. 3. `list` only has *one* element (the row number) and since you're using `len(list)` it will never work: `len(list)` returns the *length of the list* (one). 3b. `list` is a python standard object, calling a list "list" (thus overwriting that name, even if only locally) is considered bad practice. – musicamante Apr 13 '21 at 04:53
  • I am under the strong impression that you're doing things a bit randomly, trying to put together things you've read here or there, but missing a fundamental step: **studying the documentation**. If you actually did that step, you'd have already found what `len` does, or that a selection model's `currentIndex()` returns a [QModelIndex](https://doc.qt.io/qt-5/qmodelindex.html), and its `row()` function does *not* return the data it contains; similarly, there is no `setText` method for [QComboBox](https://doc.qt.io/qt-5/qcombobox.html). Studying the documentation is a requirement, *NOT* an option – musicamante Apr 13 '21 at 05:03

1 Answers1

0

Since the OP does not provide an MRE then I will create a simple demo of how you can implement the functionality of mapping the elements of the selected row of a table in various widgets.

The appropriate widgets must be chosen so that the user does not enter incorrect values, for example in the case of stock if a QLineEdit is used the user could enter a word which does not make sense since a number is expected so it is better to use a QSpinBox.

Also when the data is saved in the table it is not good to convert it to a string since it loses the way to differentiate them, it is better to save the value through setData() associated with the Qt::DisplayRole role.

Finally, the key to the solution is to use a QDataWidgetMapper that allows mapping parts of a model in widgets, so each time a row is selected the currentIndex of the mapper is updated and it sends the information to the editors.

from functools import cached_property
import random
import sys

from PyQt5 import QtCore, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    LABELS = (
        "Product ID",
        "Product Name",
        "Description",
        "Category",
        "Price",
        "Stock",
    )
    CATEGORY_OPTIONS = (
        "OPTION1",
        "OPTION2",
        "OPTION3",
        "OPTION4",
    )

    def __init__(self, parent=None):
        super().__init__(parent)

        self.mapper.setModel(self.tableWidget.model())
        self.tableWidget.selectionModel().currentChanged.connect(
            self.mapper.setCurrentModelIndex
        )

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QHBoxLayout(central_widget)

        flay = QtWidgets.QFormLayout()
        lay.addLayout(flay)
        lay.addWidget(self.tableWidget, stretch=1)

        editors = (
            self.name_edit,
            self.description_edit,
            self.category_combo,
            self.price_edit,
            self.stock_edit,
        )

        for i, (label, widget) in enumerate(zip(self.LABELS[1:], editors)):
            flay.addRow(label, widget)
            self.mapper.addMapping(widget, i)

        self.fillTable()

        self.resize(960, 480)

    @cached_property
    def tableWidget(self):
        table = QtWidgets.QTableWidget(
            0,
            len(self.LABELS),
            selectionBehavior=QtWidgets.QAbstractItemView.SelectRows,
            selectionMode=QtWidgets.QAbstractItemView.SingleSelection,
        )
        table.setHorizontalHeaderLabels(self.LABELS)
        return table

    @cached_property
    def name_edit(self):
        return QtWidgets.QLineEdit()

    @cached_property
    def description_edit(self):
        return QtWidgets.QLineEdit()

    @cached_property
    def category_combo(self):
        combo = QtWidgets.QComboBox()
        combo.addItems(["--Null--"] + list(self.CATEGORY_OPTIONS))
        combo.setCurrentIndex(0)
        return combo

    @cached_property
    def price_edit(self):
        return QtWidgets.QDoubleSpinBox(maximum=2147483647)

    @cached_property
    def stock_edit(self):
        return QtWidgets.QSpinBox(maximum=2147483647)

    @cached_property
    def mapper(self):
        return QtWidgets.QDataWidgetMapper()

    def fillTable(self):
        self.tableWidget.setRowCount(0)
        for i in range(30):
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            values = (
                i,
                f"name-{i}",
                f"Description-{i}",
                random.choice(self.CATEGORY_OPTIONS),
                random.uniform(100, 2000),
                random.randint(0, 100),
            )
            for j, value in enumerate(values):
                it = QtWidgets.QTableWidgetItem()
                it.setData(QtCore.Qt.DisplayRole, value)
                it.setFlags(it.flags() & ~QtCore.Qt.ItemIsEditable)
                self.tableWidget.setItem(i, j, it)


def main():
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241