方式一:使用 StyleSheet

1
2
3
QWidget:focus {
outline: none; /* 去掉得到焦点时的虚线框 */
}

方式二:继承 QProxyStyle

继承 QProxyStyle,PrimitiveElement 为 QStyle::PE_FrameFocusRect 时不绘制虚线框,然后在 main() 函数里调用 QApplication::setStyle() 使用新的样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 文件名: NoFocusRectStyle.h
#ifndef NOFOCUSRECTSTYLE_H
#define NOFOCUSRECTSTYLE_H
#include <QProxyStyle>
class NoFocusRectStyle : public QProxyStyle
{
public:
NoFocusRectStyle(QStyle *baseStyle) : QProxyStyle(baseStyle) {}
void drawPrimitive(PrimitiveElement element,
const QStyleOption *option,
QPainter *painter,
const QWidget *widget = 0) const
{
if (element == QStyle::PE_FrameFocusRect)
{
return;
}
QProxyStyle::drawPrimitive(element, option, painter, widget);
}
};
#endif // NOFOCUSRECTSTYLE_H
1
2
3
4
5
6
7
8
9
10
11
12
13
// 文件名: main.cpp
#include "Widget.h"
#include "NoFocusRectStyle.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
NoFocusRectStyle *style = new NoFocusRectStyle(app.style());
app.setStyle(style); // Ownership of the style object is transferred to QApplication
Widget w;
w.show();
return app.exec();
}