简体   繁体   中英

Change the color of a QRubberBand

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?

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.

The simplest way is using QGraphicsColorEffect, as follows:

QGraphicsColorizeEffect *e = new QGraphicsColorizeEffect(rubberBand_);
e->setColor(QColor("red"));
rubberBand_->setGraphicsEffect(e);

However, QGraphicsEffects are deprecated in Qt 4.8 with the reason "flawed design". Color and dropshadow effects are used extensively in my projects to render non-widget items, menus and fonts. I hope Nokia would provide equivalent solutions before deprecate the entire feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM