开发者

Problem with drawing focus frame in Qt

开发者 https://www.devze.com 2022-12-13 02:20 出处:网络
I\'m trying to create custom widget inheriting QFrame. All works fine, but I\'m unable to draw the focus rectangle around my widget. Below is the sample code I use for drawing:

I'm trying to create custom widget inheriting QFrame. All works fine, but I'm unable to draw the focus rectangle around my widget. Below is the sample code I use for drawing:

frame.h

class Frame : public QFrame {
Q_OBJECT
public:
    Frame(QWidget *parent = 0);
    ~Frame();

protected:
    void paintEvent(QPaintEvent *event);

private:
    Ui::Frame *ui;
};

frame.cpp

Frame::Frame(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::Frame)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::ClickFocus);
}

Frame::~Frame()
{
    delete ui;
}

void Frame::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);
    if (hasFocus()) {
        QStylePainter painter(this);
        QStyleOptionFocusRect option;
        option.initFrom(this);
        option.backgroundColor = palette().dark().color();
        painter.drawPrimitive(QStyle::PE_FrameFocusRect, option);
    }
}

What I mean by 'unable to draw focus frame' is that w开发者_JAVA技巧hen you click a standard widget that accepts focus (let's say QLineEdit), it has a blue rectangle drawn around it. When I click my widget there is no such rectangle drawn. Are there any more things I should do besides setting focusPolicy on my widget?


It might have something to do with the style your app is using. When I try your code with the "gtk" and "cleanlooks" style, no focus rectangle is drawn. With "plastique" and "windows" it is. Since I'm on Linux, I cannot test "windowsxp" and "macintosh". Try running with the -style option and see what happens.


try also

setFocusPolicy(Qt::StrongFocus);
setAttribute( Qt::WA_MacShowFocusRect);
0

精彩评论

暂无评论...
验证码 换一张
取 消