[Qt-interest] Insert item to QTableWidget increases the CPU usage!

Andrew Hodgkinson ahodgkinson at endurancetech.co.uk
Tue Jun 1 12:27:05 CEST 2010


On 01/06/2010 09:26, Jack Mack wrote:

> Have anybody an idea how I can solve that problem?

For each data item received, you're asking Qt to create objects and, 
possibly, Qt will call the OS to create OS-level widgets. This shouldn't 
be slow on modern (or even on old) hardware but fact is, it is, and 
either way it's an inefficient design as you're creating lots of widgets 
for parts of the table which the user probably can't even see.

I suggest you change your approach entirely. The user views your table 
through a window. The window can only be a certain size. Most likely, 
there is lots of data and the user will scroll around to see it. So why 
create thousands (even millions) of widgets, when the user can only see a 
handful at any given time? Store your incoming data in some convenient 
indexed internal raw form via e.g. a data collection thread, then:

* Paint it to the screen using custom paint routines that take account
   of the scroll offset and only worry about reading and redrawing data
   for the visible window region (if you fix the height of each row
   then you can get from y-coordinate to data row index very quickly);

...or...

* Dynamically create table widgets as the user scrolls around the page,
   but don't create widgets for invisible regions. I recommend you also
   delete widgets which are scrolled out of view, else the action of
   scrolling would create an unbounded accumulation of widgets which
   would in essence represent a memory leak (or a cache, depending on
   your perspective).

The first option will most likely be the most CPU and RAM efficient, but 
requires custom drawing routines. If you want to present data in a table 
with consistent per-OS styling or you want extra editing/manipulation 
features only available via the Qt / OS table widgets then this wouldn't 
be a good approach.

The second method will be slower, but gives you more features and 
probably requires less coding. Just how sluggish scrolling ends up 
feeling to the user will depend on how quickly Qt can create and destroy 
table rows. Frankly, if Qt can't create a window full of rows in a 
near-instantaneous fashion on today's multi-GHz CPUs, then there's 
something very, very wrong; I doubt this is the case, so you'll hopefully 
be fine doing that.

-- 
Andrew Hodgkinson, Endurance Technology
Land line: 01223 369 408, mobile: 07855 866 780
Registered Office: 5 Marine Drive West, Bognor Regis, W. Sussex, PO21 2QA



More information about the Qt-interest-old mailing list