Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update QTableWidget?

My objective is to update the QTableQidget when new contacts are added. I have no problem adding the contacts or them showing up in the QTableWidget. My problem is that I have to exit out the program and then start it up again in order to see the newly added contacts. Is their a way to update or refresh the QTableWidget to show new contacts when they are added to the database without having to quit the program. I've tried update() and repaint and nothing changes.

class BrowseContacts(QtGui.QWidget):
    #Display New Contacts Widget
    def __init__(self):
        super(BrowseContacts, self).__init__()
        self.initUI()
        self.contactsData()


    #User Interface
    def initUI(self):
        self.new_layout = QtGui.QGridLayout()

        self.contactsTableWidget = QtGui.QTableWidget()
        self.contactsTableWidget.setColumnCount(10)

        self.contacts_label = ['First Name', 'Last Name', 'Home Phone', 'Cell Phone', 'Business Name', 'Email Address', 'Address', 'City', 'State', 'Zip Code']
        self.contactsTableWidget.setHorizontalHeaderLabels(self.contacts_label)
        self.contactsTableWidget.setSortingEnabled(True)

        self.new_layout.addWidget(self.contactsTableWidget)
        self.setLayout(self.new_layout)

        self.setStyleSheet('QTableWidget::item {background-color: #ffffff; color: #000000}' 'QTableWidget::item:selected {background-color: #3aa8ad; color: #ffffff;}')

    def contactsData(self):
        #Connect to Database
        connection = sqlite3.connect('contacts.db')
        cur = connection.cursor()

        rowcount = cur.execute('''SELECT COUNT(*) FROM contacts''').fetchone()[0]

        self.contactsTableWidget.setRowCount(rowcount)
        cur.execute('''SELECT  * FROM contacts''')

        for row, contacts in enumerate(cur):
            for column, contact in enumerate(contacts):
                self.contactsTableWidget.setItem(row, column, QtGui.QTableWidgetItem(str(contact)))

        cur.close()
        connection.commit()
        connection.close()

Thank You

like image 411
irunintotrees Avatar asked Oct 18 '25 15:10

irunintotrees


1 Answers

You call contactsData() once, and it fills qtablewidget with data from database. If you want to refresh qtablewidgetyou need to call that method again. You could create pushbutton and connect it to contactsData(), so when you press that button, contacts are reloaded from your database without having to quit the program.

If you need it to be done automatically you can create timer to call contactsData().

EDIT

just add this line at the end of contactsData() method:

QtCore.QTimer.singleShot(10000, self.contactsData)

it will reload the data every 10 seconds

like image 199
Aleksandar Avatar answered Oct 21 '25 10:10

Aleksandar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!