Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableWidget Current Selection Change Signal

What's the signal of a QTableWidget when the current selection changes and how can I assign a slot to it?

like image 350
Amen Avatar asked Apr 19 '15 19:04

Amen


Video Answer


1 Answers

You want the itemSelectionChanged signal:

This signal is emitted whenever the selection changes.

You can use this by doing something like this:

self.itemSelectionChanged.connect(self.print_row)

This will call self.print_row (which is a function you create) every time the selection changes.


A very basic example:

import sys
from PyQt4 import QtGui, QtCore

lista = ['r1c1', 'r1c2', 'r1c3']
listb = ['r2c1', 'r2c2', 'r1c3']
listc = ['r3c1', 'r3c2', 'r3c3']
mystruct = {'row1':lista, 'row2':listb, 'row3':listc}

class MyTable(QtGui.QTableWidget):
    def __init__(self, thestruct, *args):
        QtGui.QTableWidget.__init__(self, *args)
        self.data = thestruct
        n = 0
        for key in self.data:
            m = 0
            for item in self.data[key]:
                newitem = QtGui.QTableWidgetItem(item)
                self.setItem(m, n, newitem)
                m += 1
            n += 1
        self.itemSelectionChanged.connect(self.print_row)

    def print_row(self):
        items = self.selectedItems()
        print(str(items[0].text()))

def main(args):
    app = QtGui.QApplication(args)
    table = MyTable(mystruct, 3, 3)
    table.show()

    sys.exit(app.exec_())

if __name__=="__main__":
    main(sys.argv)

This creates a table like this:

UI

When you select any of the cells, it will print out the text in the cell. As a note, this print function assumes that you only make one selection at a time. The selectedItems() function returns a list of selected items. I am only using the first index in this example.

like image 102
Andy Avatar answered Sep 20 '22 15:09

Andy