Search code examples
pythonpyqt5

How can I have a progress bar in a table widget spanned over two cells in PyQt5?


I have a QTableWidget with 6 columns and 6 rows (the first row is a header row). It's a stock level 2 window where the headers are ask count, ask volume, ask, bid, bid volume, and bid count.

I want to have two progress bars in each row based on the values of ask volume and bid volume, with the maximum value being the maximum of the ask and bid volume columns.

The first progress bar should span over the ask volume and ask price columns, and the second one should span over the bid price and bid volume columns. I want the ask count and bid count columns to be aligned center, ask volume to be left-aligned, and ask price to be right-aligned. Similarly, the bid price should be left-aligned, and bid volume should be right-aligned.

I can do all the work, but the problem is that when I use the command tableWidget.setCellWidget(0,1, progress_bar) to insert a progress bar in the corresponding cell, the text in the table gets replaced with the progress bar. To set the text, I have to use progress_bar.setFormat('{:,}.format()').

However, when I want to span the progress bar over two cells using tableWidget.setSpan(0,1,1,2), I can't set the text of those cells separately so that I can adjust their alignment. The only solution I've found is to use progress_bar.setFormat('{:10,} {:6,}'.format(ask_price,ask_volume)), but this doesn't allow me to adjust the alignment perfectly.

Here's an image of what I want to achieve:

enter image description here

How could I solve this?


Solution

  • Thank you for the suggestions @Carl HR, but I was able to overcome the issue using a different approach with the QStyledItemDelegate, which turned out to be much easier. Here's what I did:

    1. First, I defined two rectangles, left_rect and right_rect, to represent the areas for the left-aligned and right-aligned texts within the merged cells. I used the option.rect.adjusted(5, 0, 0, 0) and option.rect.adjusted(0, 0, -5, 0) methods to adjust the rectangles' dimensions accordingly.

    2. Next, I set the desired alignment for the left and right texts using the QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter and QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter alignment values, respectively. I stored them in variables named left_align and right_align.

    3. Finally, I used the painter.drawText(left_rect, left_align, str(value)) method to draw the left-aligned text within the left_rect area, and similarly for the right-aligned text using right_rect and right_align.