如何设置KDChart饼图项目的标签

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

本文关键字:项目 标签 KDChart 何设置 设置      更新时间:2023-10-16

是否有任何方法可以为饼图的每个项设置文本标签,该饼图是使用Qt中的KDChart库创建的?

更具体地说,在这种特殊情况下,我不使用模型/视图体系结构。我通过KDChart::Widget创建它,并仅使用Widget::setDataCell()填充图表。

似乎有几种方法可以为轴设置文本标签,但我还没有遇到类似的饼图。不管怎样,这不是我需要的东西。我想为某些点设置标签,而不是为其轴设置标签。在应用于饼图时,它将类似于标题扇区。

我想,也许通过使用带有填充值的KDChart::Legend,我可以实现所需的行为,但它没有起作用。

这是一个代码示例,也许它会有所帮助。但请记住,它已经改变了(清除了混乱的行),我还没有测试它的正确性:

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 );

还有一件事——我试图用不一致的列号(0,2,5,9等)填充它,但饼图绘制错误——一些扇区与其他扇区重叠。在其他类型的图表(例如条形图)中,所有数据都被正确地可视化。

你对商品标签有什么想法吗?

附言我已经弄清楚了跳过饼图的一些列来填充饼图的列有什么问题。如果不一致地填充列(跳过其中一些列),那么只需显式地将跳过的列的值设置为零。它将修复错误的饼图可视化问题。

也许KDChart应该自己找出跳过的列,并自动将其设置为null,但它不会。所以你自己做吧。

希望这能帮助到别人。

我自己找到了一个解决方案。考虑到KDChart库上的少量信息,我将其发布在这里,希望它能帮助有类似问题的人。

该解决方案在KDChart层次结构中占有相当深的位置。您需要手动打开标签显示。我为它创建了一个单独的函数。

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();
}

请记住,有一个较短的解决方案-如果您不需要每个标签的唯一文本参数,只需设置"全局"DataValueAttributesTextAttributesKDChart::AbstractDiagram类中有一个方法-AbstractDiagram::dataValueAttributes(),没有任何参数)。