In my application, I have a plot with a QwtLegend-based object displayed to the right. I modified the layout, so that the legend items can use as much horizontal space as possible (that's because I may, in some cases, set the width of my legend to a much bigger value than actually necessary; this is because I have other plots with legends and that I want to have everything properly aligned). For this, I do the following:

Qt Code:
  1. static_cast<QwtDynGridLayout *>(contentsWidget()->layout())->setExpandingDirections(Qt::Horizontal);
To copy to clipboard, switch view to plain text mode 

It all works fine, but now if I try to export the plot to PDF, PNG, etc. then the legend gets rendered to the very left of my plot while some space still has been allocated for my legend to the right.

I was able to reproduce the issue using the friedberg example. If I export that example, I get the following, as expected:

Good.jpg

Now, if I modify plot.cpp in the friedberg example, so that instead of having:

Qt Code:
  1. insertLegend( new QwtLegend(), QwtPlot::RightLegend );
To copy to clipboard, switch view to plain text mode 

I now have:

Qt Code:
  1. QwtLegend *legend = new QwtLegend();
  2. QwtDynGridLayout *legendLayout = qobject_cast<QwtDynGridLayout *>( legend->contentsWidget()->layout() );
  3.  
  4. if ( legendLayout )
  5. legendLayout->setExpandingDirections( Qt::Horizontal );
  6.  
  7. insertLegend( legend, QwtPlot::RightLegend );
To copy to clipboard, switch view to plain text mode 

Then, if I re-export the example, I now get the following:

Bad.jpg

I fixed the problem in my QwtLegend-based class by overriding the renderLegend() method. I basically copied/pasted the code and just after:

Qt Code:
  1. QList<QRect> itemRects =
  2. legendLayout->layoutItems( layoutRect, numCols );
To copy to clipboard, switch view to plain text mode 

I added:

Qt Code:
  1. if (legendLayout->expandingDirections() & Qt::Horizontal) {
  2. for (int i = 0, iMax = itemRects.size(); i < iMax; ++i)
  3. itemRects[i].adjust(layoutRect.left(), 0, layoutRect.left(), 0);
  4. }
To copy to clipboard, switch view to plain text mode 

Now, it all works fine for my particular needs, i.e. the legend is always rendered to the right and its layout's expanding direction is horizontal. This means that my 'fix' is likely not to work in some other cases, not to mention that a fix should be applied to QwtDynGridLayout::layoutItems() rather than QwtLegend::renderLegend()...