r/cpp • Meeting C++ | C++ Evangelist • Apr 27 '14

Writing a bar graph widget in Qt

http://meetingcpp.com/index.php/br/items/writing-a-bar-graph-widget-in-qt.html
2 Upvotes

6 comments sorted by

1

u/PZ-01 Apr 27 '14

For those looking for something more complex and reusable there's a pie chart implementation in the Qt samples. It's implemented as a View so it can be integrated with MVC for any ui.

1

u/meetingcpp Meeting C++ | C++ Evangelist Apr 27 '14

Yes, its a nice example if you use the Qt Model/Views: http://qt-project.org/doc/qt-5/qtwidgets-itemviews-chart-example.html

In my use case I don't have that, and using just a vector<int> for the display plus vector<QString> for the labels makes it very reusable for me too. In fact I already use it in 2 different places with 2 different modes.

1

u/austingwalters Apr 27 '14

I'm working on a similar application: https://github.com/lettergram/basicbookreader

I actually use vector<std::pair<QString, int> >

This allows me to store more information, such as what each bar represents, and the height of each bar.

2

u/meetingcpp Meeting C++ | C++ Evangelist Apr 27 '14 edited Apr 27 '14

Interesting. I've chosen to have this separated, as in sometimes I might not have a label or want the data to be the label.

I've seen that you've got a memleak, you must also delete the QFile pointer returned by openFile in your code. Actually there is no good reason to allocate this on the heap...

This is how I do it:

QFile file(path);
if(!file.open(QFile::WriteOnly))
    return;
QTextStream out(&file);

1

u/austingwalters Apr 27 '14

Thanks for pointing out the memory leak. I haven't taken the time to get valgrind on my mac (OSX 10.9) which apparently has issues.

It's really a "by preference" type of things, just thought you might the pair idea interesting.

1

u/meetingcpp Meeting C++ | C++ Evangelist Apr 27 '14

yes, I'm thinking how to only bind this to a data provider object, which has a int operator()(size_t index) interface. An Adapter for Qt models would then be easy.