Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of a QRubberBand

Tags:

qt

qt4

I am trying to change the color of a QRubberBand. I tried this:

QRubberBand* rubberBand = new QRubberBand(QRubberBand::Rectangle, this->graphicsView);
QPalette palette;
palette.setBrush(QPalette::Foreground, QBrush(Qt::green));
palette.setBrush(QPalette::Base, QBrush(Qt::red));

rubberBand->setPalette(palette);

rubberBand->resize(30, 30);
rubberBand->show();

but the rubberband that appears is the standard black dotted one. Any ideas on how to do this?

like image 793
David Doria Avatar asked Nov 15 '11 16:11

David Doria


1 Answers

The actual rendering depends on the platform, but for Windows (perhaps others), you set the QPalette::Highlight color role. This example works:

#include <QtGui>

int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QRubberBand band(QRubberBand::Rectangle);

  QPalette pal;
  pal.setBrush(QPalette::Highlight, QBrush(Qt::red));
  band.setPalette(pal);

  band.resize(30, 30);
  band.show();
  return app.exec();
}

If you are on a different platform, let me know and I can see what works for that platform.

However, since you refer to a graphics view, I'm wondering if you mean the black dotted line that appears around selected items? That is something completely different, and doesn't involve the QRubberBand at all. If that is the case, you might need to update the question.

BTW, I looked at the code for QWindowsVistaStyle to track down the answer. If you are on a different platform and have access to the source, you can look in the correct style class for that platform.

UPDATE Looks like you are out of luck with Ubuntu. That uses QCleanLooksStyle, which calls QWindowsStyle for a rubber band. In there, the colors are hard-coded:

QPixmap tiledPixmap(16, 16);
QPainter pixmapPainter(&tiledPixmap);
pixmapPainter.setPen(Qt::NoPen);
pixmapPainter.setBrush(Qt::Dense4Pattern);
pixmapPainter.setBackground(Qt::white);
pixmapPainter.setBackgroundMode(Qt::OpaqueMode);
pixmapPainter.drawRect(0, 0, tiledPixmap.width(), tiledPixmap.height());
... etc ...

Also, the Qt Style Sheets Reference doesn't list QRubberBand as obeying any styles. If you really need a different color, your only option might be to subclass QRubberBand and implement paintEvent. Bummer.

like image 118
Dave Mateer Avatar answered Oct 09 '22 18:10

Dave Mateer