有一个困扰我的问题,也许对你们来说这只是一个简单的问题。我想在Qt小部件中绘制拖线,当QComboBox cbx
设置为项目1时,第一行设置为红色,第二个黑色,相反,第二行设置为红色,第二个黑色。我用*paintEvent*
画了线。 (实际上,如果要绘制某些东西,必须绘制paintEvent
函数),但是我不知道如何根据QComboBox
项目更改线条的颜色,以下是我的代码。
#include "changecolor.h"
#include "ui_changecolor.h"
QString st;
QPainter painter;
ChangeColor::ChangeColor(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ChangeColor)
{
ui->setupUi(this);
setFixedSize(2000, 1000);
QComboBox * cbx = new QComboBox(this);
cbx->setSizeAdjustPolicy(QComboBox::AdjustToContents);
cbx->addItem("1", Qt::DisplayRole);
cbx->addItem("2", Qt::DisplayRole);
st = cbx->currentText();
connect(cbx, SIGNAL(currentTextChanged(QString)), this, SIGNAL(changeColorSlot(st, painter)));
}
void ChangeColor::paintEvent(QPaintEvent*)
{
// QPainter painter(this);
// painter.setPen(Qt::black);
// painter.drawLine(QPoint(100,100), QPoint(1100,100));
// painter.drawLine(QPoint(100,100), QPoint(100,600));
// changeColorSlot(painter, );
changeColorSlot(st, painter);
}
void ChangeColor::changeColorSlot(QString& st, QPainter& painter)
{
// QPainter painter(this);
if(st == tr("1"))
{
painter.setPen(Qt::black);
painter.drawLine(QPoint(100,100),QPoint(1100,100));
painter.setPen(Qt::red);
painter.drawLine(QPoint(100,100),QPoint(100,600));
}
else if(st == tr("2"))
{
painter.setPen(Qt::red);
painter.drawLine(QPoint(100,100),QPoint(1100,100));
painter.setPen(Qt::black);
painter.drawLine(QPoint(100,100),QPoint(100,600));
}
update();
}
ChangeColor::~ChangeColor()
{
delete ui;
}
这些代码表示我痛苦的编码生活,我的意思是我已经尝试了很多次,但是没有正确的结果。谢谢你们。
我想您正在寻找此功能:
QComboBox* cb = ...;
QAbstractItemView* view = cb->view();
view->setAlternatingRowColors(true);
您必须设置控制小部件外部状态(线条颜色)的逻辑:
这里是有关部分的示例
。h:#include
namespace Ui
{
class ChangeColor;
}
class ChangeColor : public QWidget
{
Q_OBJECT
public:
explicit ChangeColor(QWidget *parent = nullptr);
void paintEvent(QPaintEvent* pe);
~ChangeColor();
public slots:
void setColorState(int state);
private:
Ui::ChangeColor* ui{nullptr};
int state{};
};
.cpp
...
void ChangeColor::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter paint(this);
QColor RED_COLOR{255, 0, 0};
QColor BLACK_COLOR{0, 0, 0};
if(state == 0)
{
paint.setPen(QPen(RED_COLOR));
paint.setBrush(RED_COLOR);
}
else
{
paint.setPen(QPen(BLACK_COLOR));
paint.setBrush(BLACK_COLOR);
}
paint.drawLine(0, 0, width(), height());
}
void ChangeColor::setColorState(int state)
{
this->state = state;
update();
}