在自定义小部件中,我想绘制连接QPainter
中按钮的行(使用QGridLayout
)。线条应位于按钮后面,以便
考虑来自BeautifulSoup的想法,我几乎可以实现在我的GUI应用程序中运行的简单基本版本(源代码如下)。
只要我使用标准Qt样式的QPushButton
,它就像魅力(左),但是,因为我想使用自定义样式,所以线条重叠(右):
导致此行为的属性或机制是什么?
MyFrame.h:
#include <QFrame>
class MyFrame : public QFrame
{
public:
MyFrame();
virtual ~MyFrame() = default;
};
MyFrame.cpp:
#include "MyFrame.h"
#include "LineDrawWidget.h"
#include <QVBoxLayout>
#include <QGridLayout>
#include <QPushButton>
#include <QButtonGroup>
MyFrame::MyFrame()
{
auto* mainLayout = new QVBoxLayout(this);
auto* buttonLayout = new QGridLayout();
QPushButton* button;
auto* buttons = new QButtonGroup();
for (int i = 0; i < 3; ++i) {
button = new QPushButton();
button->setText(QString::number(i+1));
button->setFixedHeight(40);
button->setFixedWidth(40);
button->setStyleSheet("QPushButton { color : black; background-color : white; }");
button->setStyleSheet("QPushButton { border-style : outset; border-color: black; border-width: 2px; border-radius: 6px; }");
buttonLayout->addWidget(button);
buttons->addButton(button, i);
}
auto* lineDraw = new LineDrawWidget(
buttons->button(0),
buttons->button(2));
lineDraw->setLayout(buttonLayout);
mainLayout->addWidget(lineDraw);
}
LineDrawWidget.h:
#include <QWidget>
class LineDrawWidget : public QWidget
{
public:
LineDrawWidget(
QWidget* from,
QWidget* to,
QWidget* parent = nullptr);
virtual ~LineDrawWidget() = default;
protected:
virtual void paintEvent(QPaintEvent* e) final override;
private:
QWidget* _from;
QWidget* _to;
};
LineDrawWidget.cpp:
#include "LineDrawWidget.h"
#include <QPainter>
LineDrawWidget::LineDrawWidget(
QWidget* from,
QWidget* to,
QWidget* parent) :
QWidget(parent),
_from(from),
_to(to)
{
}
void LineDrawWidget::paintEvent(QPaintEvent* e)
{
(void)e;
QPainter painter(this);
QPoint start = _from->mapToGlobal(_from->rect().bottomLeft());
QPoint end = _to->mapToGlobal(_to->rect().topRight());
painter.drawLine(mapFromGlobal(start), mapFromGlobal(end));
}
答案 0 :(得分:1)
我认为问题是单个setStyle
对QPushButton
的两次单独调用 - 第二次调用似乎会重置其中不存在的所有属性。试着把它全部放在一个电话中......
button->setStyleSheet("color : black; background-color : white; border-style : outset; border-color: black; border-width: 2px; border-radius: 6px;");
似乎适合我。