How can I avoid drawing the focus rect on my buttons?

In order to not draw the focus rect of the buttons it is necessary to subclass the style and reimplement QStyle::drawControl() [qt.nokia.com] to strip out the State_HasFocus [doc.qt.nokia.com] state for the buttons.

See the following example:

  1. #include <QtGui>
  2.  
  3. class Style : public QWindowsStyle
  4. {
  5. public:
  6.   Style()
  7.   {}
  8.   void drawControl ( ControlElement element, const QStyleOption * option,
  9.     QPainter * painter, const QWidget * widget = 0 ) const
  10.   {
  11.     if(element == CE_PushButton) {
  12.       const QStyleOptionButton *b = qstyleoption_cast<const QStyleOptionButton *>(option);
  13.       if (btn) {
  14.         if (btn->state & State_HasFocus) {
  15.           btn->state = btn->state ^ State_HasFocus;
  16.         }
  17.       }
  18.       QWindowsStyle::drawControl(element, btn, painter, widget);
  19.  
  20.     } else {
  21.       QWindowsStyle::drawControl(element, option, painter, widget);
  22.     }}};
  23.  
  24. int main(int argc, char **argv)
  25. {
  26.   QApplication app(argc, argv);
  27.  
  28.   QWidget box;
  29.   QPushButton *button1 = new QPushButton(&box);
  30.   button1->setText("Number one");
  31.  
  32.   QPushButton *button2 = new QPushButton(&box);
  33.   button2->setText("Number two");
  34.  
  35.   button1->setStyle(new Style());
  36.   button2->setStyle(new Style());
  37.  
  38.   QVBoxLayout *layout = new QVBoxLayout(&box);
  39.   layout->addWidget(button1);
  40.   layout->addWidget(button2);
  41.  
  42.   box.show();
  43.   return app.exec();
  44. }
  45.  

No comments

Write a comment

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