When setting a background pixmap for a widget, it is tiled if the pixmap is smaller than the widget. Is there a way to avoid this?

In order to avoid the image from being tiled, you can catch the resizeEvent() [doc.qt.nokia.com] and scale it to fit the size of the widget. The example below illustrates how this can be done. It creates a new image the same size as the widget, fills it with gray, and then draws the background image centered on it, with the aspect ratio preserved.

  1. #include <QtGui>
  2.  
  3. class MdiArea : public QMdiArea
  4. {
  5.         Q_OBJECT
  6. public:
  7.         MdiArea()
  8.         {
  9.                 i = QImage("logo.png");
  10.         }
  11. protected:
  12.         void resizeEvent(QResizeEvent *resizeEvent)
  13.         {
  14.                 QImage newBackground(resizeEvent->size(), QImage::Format_ARGB32_Premultiplied);
  15.                 QPainter p(&newBackground);
  16.                 p.fillRect(newBackground.rect(), Qt::gray);
  17.  
  18.                 QImage scaled = i.scaled(resizeEvent->size(),Qt::KeepAspectRatio);
  19.                 QRect scaledRect = scaled.rect();
  20.                 scaledRect.moveCenter(newBackground.rect().center());
  21.                 p.drawImage(scaledRect, scaled);
  22.                 setBackground(newBackground);
  23.                 QMdiArea::resizeEvent(resizeEvent);
  24.         }
  25. private:
  26.         QImage i;
  27. };
  28.  
  29. #include "main.moc"
  30. int main(int argc, char **argv)
  31. {
  32.         QApplication app(argc, argv);
  33.         MdiArea box;
  34.         box.resize(400, 400);
  35.         box.show();
  36.         return app.exec();
  37. }

No comments

Write a comment

Sorry, you must be logged in to post a comment.