How it works…

The table widget is similar to the one you see in spreadsheet applications such as Microsoft Excel and OpenOffice Calc. In contrast with other types of model viewers, such as list view or tree view, table view (or table widget) is a two-dimensional model viewer, which displays data in the form of rows and columns.

The main difference between a table view and a table widget in Qt is that a table widget is built on top of a table view class, which means a table widget is easier to use and more suitable for beginners. However, a table widget is less flexible and tends to be less scalable than a table view, which is not the best choice if you want to customize your table.

After retrieving data from MySQL, we created a QTableWidgetItem item for each of the data items and set which column and row should be added to the table widget. Before adding an item to the table widget, we must increase the row count of the table by calling QTableWidget::setRowCount(). We can also get the current row count of the table widget by simply calling QTableWidget::rowCount().

The first column from the left is hidden from view because we only use it to save the ID of the data so that we can use it to update the database when one of the data items in its row has changed. The on_tableWidget_itemChanged() slot function will be called when the data in one of the cells has changed. It will not only get called when you edit the data in the cell, but also when the data is first added to the table after being retrieved from the database. To ensure that this function is only triggered when we edit the data, we use a Boolean variable called hasInit to check whether we have done the initialization process (adding the first batch of data to the table). If hasInit is false, ignore the function call.

To prevent users from entering a totally irrelevant type of data, such as inserting letters into a numerical-only data cell, we manually check whether the data is anything close to what we'd expected when it's being edited. Revert it to a default value if it doesn't come close to anything considered valid. This is, of course, a simple hack, which does the job but is not the most professional method. Alternatively, you can try to create a new class that inherits the QItemDelegate class and define how your model view should behave. Then, call QTableWidget::setItemDelegate() to apply the class to your table widget.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset