我需要将多个自定义的 QPushButton
子类实例相邻地放置在一起。但是,当绘制时,这些按钮会重叠在一起。以下是该问题的简化示例。
这里是(不正确的)输出:
#include <QtGui>
class MyButton : public QPushButton {
public:
explicit MyButton(Qt::GlobalColor color, QWidget *parent = NULL)
: QPushButton(parent), color_(color) {
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}
QSize sizeHint() const {
return QSize(50, 25);
}
protected:
void paintEvent(QPaintEvent *) {
QPainter painter(this);
painter.setOpacity(0.5);
painter.fillRect(0, 0, width(), height(), color_);
}
private:
Qt::GlobalColor color_;
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
QWidget widget;
QHBoxLayout *layout = new QHBoxLayout;
layout->setSpacing(0);
MyButton *w1 = new MyButton(Qt::red);
MyButton *w2 = new MyButton(Qt::green);
MyButton *w3 = new MyButton(Qt::blue);
layout->addWidget(w1);
layout->addWidget(w2);
layout->addWidget(w3);
widget.setLayout(layout);
widget.show();
return app.exec();
}
什么导致了这个问题,我该如何修复它?顺便说一句,我尝试过使用常规的QWidget子类(而不是QPushButton子类)进行类似的操作,没有问题。这是特定于QPushButton的东西。
更新:我现在真的认为这是一个错误。我将其提交到Qt Bug Tracker;我们将看看Trolls的想法。无论如何,从QAbstractButton派生可以解决绘图问题...我只需要重新实现一些所需的功能。
更新2:Qt的巨魔们提供了一个解决方案(变通方法?);我将他们的解决方案发布为下面的答案。我把这个问题交给他们的团队来确定这是一个功能还是一个错误。显然,它在Mac上的行为有所不同。