Draw a pie chart in MFC TeeChart - c++

My English is no very good, so please forgive me. I have added my data successfully in a pie chart, but the pie chart doesn't show with only data shown in the control.
The properties of the control seem like have been configured appropriately. I don't know where is the problem since I have spent whole my night on it.
BOOL CStatInfPieDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
char temp1[100];
char temp2[100];
CString str;
// TODO: Add extra initialization here
CSeries series = (CSeries)statInfPie.Series(0);
int size = stationInfList.size();
series.put_ColorEachPoint(true);
srand(time(NULL));
for (int i = 0; i < size; i++) {
sprintf(temp1, "%s/%d ", iptostr(stationInfList[i].netaddrA), toCidr(stationInfList[i].netmaskA));
sprintf(temp2, "%s/%d", iptostr(stationInfList[i].netaddrB), toCidr(stationInfList[i].netmaskB));
strcat(temp1, temp2);
str = CString(temp1);
series.Add(stationInfList[i].bcountAToB + stationInfList[i].bcountBToA, str, RGB(rand() % 255, rand() % 255, rand() % 255));
memcpy(temp1, "\0", sizeof(temp1));
memcpy(temp2, "\0", sizeof(temp2));
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
The code sample above initializes my dialog which contains the TeeChart control. I add data through function Add(). Array temp1 and array temp2 is my description inf. After I compile and run my program, the result shows in the picture blow.

TeeChart tries to make space for the long labels and the Legend, automatically reducing the diameter of the Pie. In this case the result is extreme; the Pie is left with no radius.
That can be resolved in one of several ways:
The latest version of TeeChart (AX) includes a property called InsideSlice for PieMarks.
ie.TChart1.Series(0).asPie.PieMarks.InsideSlice = True
For older versions of TeeChart, where this property is not available you can manually set the Arrowlength (the connector to the Mark) to a negative value:
ie. TChart1.Series(0).Marks.ArrowLength = -20
The Series Marks can be setup to render multiline, taking up less width:
ie. TChart1.Series(0).Marks.MultiLine = True
If the Legend is in the Chart with very long labels that can also be counter productive to chart readability. The Legend can be set to Visible false or told to not resize the Chart Series (the Pie) to fit.
ie. TChart1.Legend.ResizeChart = False
or can be positioned below the Pie
ie. TChart1.Legend.Alignment = laBottom
A thought to design will be required here. Showing long Point Value labels (the Series Marks) and repeating some of the information in the Legend is taking up a great deal of the working space where the Chart could be shown. If the Legend were to be placed below the Chart and the Panel were sized accordingly and perhaps were to use information that doesn't duplicate the Series Marks' information (using a different Legend Text Style) plus setting up the Series Marks with Multiline, with a shorter Arrowlength, then the overall result should be very readable.

Related

Wrapping text in GTK3 treeview

I have trouble getting TreeView in GTK3 to wrap text correctly.
I set it up to wrap in this way:
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_mode().set_value(Pango::WRAP_WORD_CHAR);
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_width().set_value(200);
This works, text is wrapped, but when I resize the window and make it bigger, there is a lot of ugly white-space above and below cell with long text. It seems, that GTK reserves height for cell based on wrap width. Which makes no sense to me.
I tried to get around with setting needed in signal_check_resize with calculating needed width like this:
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
auto width = this->get_allocated_width()
- mTreeView.get_column(0)->get_width()
- mTreeView.get_column(1)->get_width();
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_width().set_value(width-100);
this->forceRecreateModel = true; //Needed to work
But this lets me only make window bigger. It cannot be shrinked, after it was resized.
The question is, how this is properly done?
I am using gtk3.20.3-1 and gtkmm3.20.1-1 on Arch linux.
EDIT: fixed typo in the title...
In the end I found how to do it.
In the setup of the window (for me constructor of the window derived class) it was necessary to set column to be AUTOSIZE in order to allow shrinking of the width.
//Last Column setup
{
mTreeView.append_column("Translation", mColumns.mEnglish);
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_mode().set_value(Pango::WRAP_WORD_CHAR);
}
Also there is needed to set correct wrap width on every resize. Without this, height of the row was as big as it would be necessary for currently set wrap_width with no regard on current width (resulting in big padding on the top, when stretched more and prohibiting to make window smaller).
This code was also in the constructor.
this->signal_check_resize().connect([this]()
{
//calculate remaining size
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
auto width = this->get_allocated_width()
- mTreeView.get_column(0)->get_width()
- mTreeView.get_column(1)->get_width()-30;
//minimum reasonable size for column
if(width < 150)
width = 150;
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_width().set_value(width);
//debounce
static auto oldsize = 0;
{
oldsize = width;
//trigger redraw of mTreeView (by clearing and refilling Model,
//it is done in 100ms pulse)
this->mRedrawNeeded = true;
}
});
And maybe it is worth noting, that I have mTreeView encapsulated in Gtk::ScrolledWindow. So this is a chunk which comes before column setup. :)
//in class is: Gtk::ScrolledWindow mScrollForResults;
//scrolling area
mGrid.attach(mScrollForResults, 0,2,10,1);
mScrollForResults.set_hexpand();
mScrollForResults.set_policy(Gtk::PolicyType::POLICY_AUTOMATIC,
Gtk::PolicyType::POLICY_ALWAYS);
mScrollForResults.set_margin_top(10);
mScrollForResults.set_min_content_width(400);
mScrollForResults.set_min_content_height(200);
mScrollForResults.add(mTreeView);
//results treeView
mRefListStore = Gtk::ListStore::create(mColumns);
mTreeView.set_model(mRefListStore);
mTreeView.set_hexpand();
mTreeView.set_vexpand();

Firemonkey: Shrink text font to fit in TLabel

I am attempting to lower the font size of a TLabel if its text is to large to fit in the confines of the label. I didn't see any properties I could set on the label to achieve this, so I have tried writing my own method. My method works by using TCanvas.TextWidth to measure the width of the text in a label, and shrink the font until the width of the text fits within the width of the label.
void __fastcall ShrinkFontToFitLabel( TCanvas * Canvas, TLabel * Label )
{
float NewFontSize = Label->Font->Size;
Canvas->Font->Family = Label->Font->Family;
Canvas->Font->Size = NewFontSize;
while( Canvas->TextWidth( Label->Text ) > Label->Width && NewFontSize > MinimumFontSize )
{
NewFontSize -= FontSizeDecrement;
Canvas->Font->Size = NewFontSize;
}
Label->Font->Size = NewFontSize;
}
This works some of the time, however other times it does not shrink the font near enough. It seems as if the value I get from calling Canvas->TextWidth is a lot of times, much smaller than the number of pixels wide the label actually needs to be in order to fit the text.
Am I using Canvas->TextWidth incorrectly? Is there a better way to calculate the width of a string, or to re-size the font of a TLabel so its text fits within its demensions?
Edit:
In this case, I am passing in to my function, the TCanvas that my label is sitting in. I have tried using that TCanvas as well as Label->Canvas. Both give me the same number for text width, and both are short of the actual value in pixels needed to display the whole string.
The following code is taken from code that works in an FMX application, modified slightly to remove arrays that are being iterated through and declaring a variable locally to the function. It is being run in a TForm method. Canvas here is the Form's Canvas. You can see that I'm using "- 35" at one point - this might be because the numbers weren't quite right.
double InitialFontSize = 30;
Canvas->Font->Size = InitialFontSize;
StoryHeadlineLabel->Font->Size = InitialFontSize;
bool fits = false;
do
{
double widthA = Canvas->TextWidth (StoryHeadlineLabel->Text);
if (widthA > StoryHeadlineLabel->Width - 35)
{
StoryHeadlineLabel->Font->Size --;
Canvas->Font->Size --;
}
else
fits = true;
if (StoryHeadlineLabel->Font->Size < 6)
fits = true;
} while (!fits);

raphael pie chart always blue when there is only 1 value (how to set color of a pie with one slice)

I am having an issue with raphael pie charts. The data I am using is dynamic, and in some instances, only 1 value is returned, meaning the whole chart is filled, as it is the ONLY slice. The problem is that when there is only 1 value, it ignores my color designation.
For example: Below is the creation of a raphael pie chart with 2 values, and each slice has the proper color designated in the "colors" section:
var r = Raphael("holder");
r.piechart(160, 136, 120, [100,200],{colors: ["#000","#cecece"]});
This works fine, and I get two properly sized slices, one black, and one grey.
However the example below creates one full pie, ALWAYS filled with blue, regardless of my color setting.
var r = Raphael("holder");
r.piechart(160, 136, 120, [100],{colors: ["#000"]});
In this situation, I really need that full pie to be black, as it is set in "colors"
Am I doing something wrong, or is this a bug?
INMO its a bug cause when the pie got only one slice its color is hard coded...
Here is how I solved it (all I did is use the colors arg if it exist...)
in g.pie.js after line 47 add this
var my_color = chartinst.colors[0];
if(opts.colors !== undefined){
my_color = opts.colors[0];
}
then in the following line (line 48 in the original js file)
series.push(paper.circle(cx, cy, r).attr({ fill: chartinst.colors[0]....
replace the chartinst.colors[0] with my_color
that's it
if (len == 1) {
var my_color = chartinst.colors[0];
if(opts.colors !== undefined){
my_color = opts.colors[0];
}
series.push(paper.circle(cx, cy, r).attr({ fill: my_color, ....
You've probably figured this out on your own since this question is already a day old... but you can "trick" Raphael into rendering a black unit by special-casing datasets of one to add an infinitesimal second value. So, given an array data with your data points...
if ( data.length == 1 )
data.push( 0.000001 );
canvas.piechart(250, 250, 120, data, {colors: ["#000", "#CECECE", "#F88" /*, ... */ ] });
The tiny sliver will still be rendered as a single-pixel line in the 180 degree position, but you could probably fudge that by playing with your color palette.
Yes, it's a trick. I don't believe gRaphael's behavior is buggy so much as poorly implemented (single-element datasets are obviously special cased since they produce a circle instead of a path as they would in all other cases).
Easy way for me without edit g.pie.js
var r = Raphael('st_diagram');
r.piechart(140, 140, 137, 100, 0.0001],{
colors:['#9ae013','#9ae013'],
strokewidth: 0
});

How to set labels for items of a KDChart pie diagram?

Is there any way to set text labels for each item of a pie diagram, created using KDChart lib in Qt?
To be more specific, I'm not using the Model/View architecture in this particular case. I create it though KDChart::Widget and merely fill the chart using Widget::setDataCell().
Seemingly there are several ways to set text labels for axis, but I haven't encountered something similar for a pie diagram. Anyway it's not the thing I need. I want to set labels for certain points rather than for its axis. In apply to a pie diagram it would be something like titled sectors.
I thought that maybe with using KDChart::Legend with filled values I can achieve required behavior, but it haven't worked.
Here is a code sample, maybe it will help somewhat. But keep in mind that it's changed (cleared of cluttering lines) and I haven't tested its correctness:
KDChart::Widget* newChart = new KDChart::Widget;
newChart->setType( KDChart::Widget::Pie );
int curColNo = 0; // it's not a size_t 'coz setDataCell requires an int
for( QVector::const_iterator curValueIt = response.begin(); curValueIt != response.end(); ++curValueIt )
{
newChart->setDataCell( 0, curColNo, *curValueIt );
newChart->diagram()->setBrush( curColNo++, QBrush( m_responsesColors[curValueIt] ) );
m_legend->addDiagram( newChart->diagram() );
}
m_mainLayout.addWidget( newChart, m_curLayoutRowNo, m_curLayoutColNo );
One more thing - I tried to fill it with inconsistent column numbers (0,2,5,9,etc) and pie chart was drawn incorrectly - some sectors overlapped others. In other types of charts (bar chart, for example) all data was visualized correctly.
Do you have any ideas about item labels?
P.S. I've figured out what's wrong with filling Pie chart's columns with skipping some of them. If you fill columns inconsistently (skipping some of them), then just set those skipped columns' values to zero explicitly. It will fix problems with wrong pie chart's visualizing.
Probably KDChart should figure out about skipped columns by itself and set it to null automatically, but it won't. So do it yourself.
Hope, this will help someone.
I have found a solution by my own. Considering a small amount of info on KDChart library, I'm posting it here in hope it will help someone with similar problem.
The solution lies quite deeply in the KDChart hierarchy. You need to manually turn on labels display. I've created a separated function for it.
void setValuesVisible( KDChart::AbstractDiagram* diagram, bool visible ) throw()
{
const QFont font( QFont( "Comic", 10 ) ); // the font for all labels
const int colCount = diagram->model()->columnCount();
for ( int iColumn = 0; iColumn < colCount; ++iColumn )
{
//QBrush brush( diagram->brush( iColumn ) ); // here you can get a color of the specified column
KDChart::DataValueAttributes a( diagram->dataValueAttributes( iColumn ) );
KDChart::TextAttributes ta( a.textAttributes() );
ta.setRotation( 0 );
ta.setFont( font );
ta.setAutoRotate( true );
//ta.setPen( QPen( brush.color() ) ); // here you can change a color of the current label's text
ta.setVisible( visible ); // this line turns on labels display
a.setTextAttributes( ta );
a.setVisible( true );
diagram->setDataValueAttributes( iColumn, a);
}
diagram->update();
}
Keep in mind, that there is shorter solution - just set TextAttributes of the "global" DataValueAttributes (there is a method for it in the KDChart::AbstractDiagram class - AbstractDiagram::dataValueAttributes() without any params) if you don't need unique text parameters for each label.

Cannot get text with Unicode (including Chinese) characters to line up with MFC using a CRichEditCtrl

I have a CRichEditCtrl (actually I have a class that is a subclass of a CRichEditCtrl, a class that I defined) that is populated by many lines of text with both horizontal and vertical scroll bars. The purpose of this control is to display a string that is searched for in a larger text along with n characters to the right and left (e.g. if the user searches for "the" then they would get a list of all the instances of "the" in the text with (if n = 100) 100 characters to the left and right of each found instance to provide context).
The query string needs to be lined up between each row. Before this program had Unicode support, just setting the font to Courier did the trick, but now that I've enabled Unicode support, this no longer works.
I've tried using monospaced fonts, but as far as I can tell, there aren't any that are for all characters. It seems to me that the latin characters all have one size, and the Chinese characters have another (I've noticed lines of text with all latin characters line up and ones with all Chinese characters line up, but ones with both do not line up).
I've also tried center aligning the text. Since the query string in each line is in the exact center, they should all line up, but I cannot seem to get this to work, the SetParaFormat call seems to just get ignored. Here's the code I used for that:
long spos, epos;
GetSel(spos, epos);
PARAFORMAT Pfm;
GetParaFormat(Pfm);
Pfm.dwMask = (Pfm.dwMask | PFM_ALIGNMENT);
Pfm.wAlignment = PFA_CENTER;
SetSel(0, -1);
SetParaFormat(Pfm);
SetSel(spos, epos);
I do this everytime text is inserted in the ctrl, but it has no affect on the program.
Is there anyway to get the query word in each line of text to line up even when there are interspersed Chinese and latin characters? (and possibly any other character set)
See http://msdn.microsoft.com/en-us/library/bb787940(v=vs.85).aspx, in particular the cTabCount and rgxTabs members of the PARAFORMAT (or PARAFORMAT2) structure, which allow you to set tabstops.
Okay so I managed to solve it. For future reference, here's what I did:
First, I tried to find a monospaced font, but I was unable to find any that were truly monospaced (had latin and chinese characters as the same width).
Next, I tried to center the text in the window. I was unable to do this until I realized that having Auto HScroll set to true (ES_AUTOHSCROLL defined for the rich edit control) caused setParaFormat to ignore me trying to center the text. After I disabled it and manually set the size of the drawable text area, I was able to center the text. Just in case anyone is curious, here's the code I used to set the width of the drawable area in the rich edit box:
CDC* pDC = GetDC();
long lw = 99999999;
SetTargetDevice(*GetDC(), lw);
I just set lw arbitrarily large so I could test to see if centering the text worked. It did not. As it turns out, when the rich edit control centers the text, it bases it off the draw width of the text, not off the number of characters. I assumed that since there were the same number of characters on either side of the query string then that would cause the string to be centered, but this was not the case.
The final solution I tried was the one suggested by ymett. After some tweaking I came up with a function called alignText() that's called after all the text has been inserted into the rich edit control. Here's the function (Note: each line in the control had tabs inserted before this function was called: one at the beginning of the line and one after the query string e.g. "string1-query-string2" becomes "\tstring1-query\t-string2")
void CFormViewConcordanceRichEditCtrl::alignText()
{
long maxSize = 0;
CFont font;
LOGFONT lf = {0};
CHARFORMAT cf = {0};
this->GetDefaultCharFormat(cf);
//convert a CHARFORMAT struct into a LOGFONT struct
if (cf.dwEffects & CFE_BOLD)
lf.lfWeight = FW_BOLD;
else
lf.lfWeight = FW_NORMAL;
if (cf.dwEffects & CFE_ITALIC)
lf.lfItalic = true;
if (cf.dwEffects & CFE_UNDERLINE)
lf.lfUnderline = true;
if (cf.dwEffects & CFE_STRIKEOUT)
lf.lfStrikeOut = true;
lf.lfHeight = cf.yHeight;
_stprintf(lf.lfFaceName, _T("%s"), cf.szFaceName);
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
font.CreateFontIndirect(&lf);
//create a display context
CClientDC dc(this);
dc.SetMapMode(MM_TWIPS);
CFont *pOldFont = dc.SelectObject(&font);
//find the line that as the longest preceding string when drawn
for(int i = 0; i < m_pParent->m_nDataArray; i++)
{
CString text = m_pParent->DataArray[i].text.Left(BUFFER_LENGTH + m_pParent->generateText.GetLength());
text.Replace(_T("\r"), _T(" "));
text.Replace(_T("\n"), _T(" "));
text.Replace(_T("\t"), _T(" "));
CRect rc(0,0,0,0);
dc.DrawText(text, &rc, DT_CALCRECT);
int width = 1.0*cf.yHeight/fabs((double)rc.bottom - rc.top)*(rc.right - rc.left);
width = dc.GetTextExtent(text).cx;
if(width > maxSize)
maxSize = width;
}
dc.SelectObject(pOldFont);
//this calulates where to place the first tab. The 0.8 is a rought constant calculated by guess & check, it may be innacurate.
long tab = maxSize*0.8;
PARAFORMAT pf;
pf.cbSize = sizeof(PARAFORMAT);
pf.dwMask = PFM_TABSTOPS;
pf.cTabCount = 2;
pf.rgxTabs[0] = tab + (2 << 24); //make the first tab right-aligned
pf.rgxTabs[1] = tab + 25;
//this is to preserve the user's selection and scroll positions when the selection is changed
int vScroll = GetScrollPos(SB_VERT);
int hScroll = GetScrollPos(SB_HORZ);
long spos, epos;
GetSel(spos, epos);
//select all the text
SetSel(0, -1);
//this call is very important, but I'm not sure why
::SendMessage(GetSafeHwnd(), EM_SETTYPOGRAPHYOPTIONS, TO_ADVANCEDTYPOGRAPHY, TO_ADVANCEDTYPOGRAPHY);
this->SetParaFormat(pf);
//now reset the user's selection and scroll positions
SetSel(spos, epos);
::SendMessage(GetSafeHwnd(),
WM_HSCROLL,
(WPARAM) ((hScroll) << 16) + SB_THUMBPOSITION,
(LPARAM) NULL);
::SendMessage(GetSafeHwnd(),
WM_VSCROLL,
(WPARAM) ((vScroll) << 16) + SB_THUMBPOSITION,
(LPARAM) NULL);
}
Essentially what this function does is make the first tab stop right-aligned and set it at some point x to the right in the control. It then makes the second tab stop a small distance to the right of that, and makes it left-aligned. So all the text from the beginning of each line to the end of the query string (from the first \t to the second \t) is pushed toward the right against the first tab stop, and all the remaining text is pushed toward the left against the second tab stop, causing the query string to be aligned between all the lines in the control. The first part of the function finds out x (by finding out how long each line will be drawn and taking the max) and the second part sets the tab stops.
Thanks again to ymett for the solution.