Skip to content

Commit

Permalink
Added controls to change text and background color.
Browse files Browse the repository at this point in the history
Added copyright to all source files.
  • Loading branch information
virxkane committed Jan 14, 2019
1 parent 833055e commit 5831765
Show file tree
Hide file tree
Showing 13 changed files with 580 additions and 6 deletions.
2 changes: 2 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ set(SRC_LIST
mainwnd.ui
lowlevel_textrender.cpp
lowlevel_textrender_private.cpp
colorbox.cpp
colorbox_private.cpp
)

set(LDADD_LIBS)
Expand Down
172 changes: 172 additions & 0 deletions src/colorbox.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/***************************************************************************
* Copyright (C) 2002-2019 by Chernov A.A. *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/

#include "colorbox.h"

#include <QtGui/QPainter>

#include <QtWidgets/QLayout>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QStyle>
#include <QtWidgets/QColorDialog>

#include "colorbox_private.h"

// class QColorBox
QColorBox::QColorBox(QWidget *parent)
: QFrame(parent)
{
setFrameStyle(QFrame::NoFrame);

layout = new QHBoxLayout(this);
comboBox = new QColorComboBox(this);
layout->addWidget(comboBox, 0);
tool = new QToolButton(this);
tool->setText(tr("..."));
layout->addWidget(tool, 0);
customColor = QColor(0, 0, 0);
defaultColor = QColor(0, 0, 0);
fill();

connect(comboBox, SIGNAL(activated(int)), SLOT(slotChanged(int)));
connect(tool, SIGNAL(clicked()), this, SLOT(slotSelColor()));
}

#define COLORTBL_SZ 16

void QColorBox::fill()
{
static const int color_tbl[COLORTBL_SZ][3] =
{
{ 255, 255, 255 },
{ 192, 192, 192 },
{ 128, 128, 128 },
{ 0, 0, 0 },
{ 255, 0, 0 },
{ 128, 0, 0 },
{ 0, 255, 0 },
{ 0, 128, 0 },
{ 0, 0, 255 },
{ 0, 0, 128 },
{ 255, 255, 0 },
{ 128, 128, 0 },
{ 0, 255, 255 },
{ 0, 128, 128 },
{ 255, 0, 255 },
{ 128, 0, 128 },
};
comboBox->insertItem(0, tr("default"));
comboBox->setItemData(0, defaultColor, Qt::BackgroundRole);
comboBox->setItemData(0, defaultColor, Qt::DecorationRole);
QColor c;
for (int i = 0; i < COLORTBL_SZ; i++)
{
c = QColor(color_tbl[i][0], color_tbl[i][1], color_tbl[i][2]);
comboBox->insertItem(i + 1, /*c.name()*/QString());
comboBox->setItemData(i + 1, c, Qt::BackgroundRole);
comboBox->setItemData(i + 1, c, Qt::DecorationRole);
}
comboBox->insertItem(COLORTBL_SZ + 1, tr("custom"));
comboBox->setItemData(COLORTBL_SZ + 1, customColor, Qt::BackgroundRole);
comboBox->setItemData(COLORTBL_SZ + 1, customColor, Qt::DecorationRole);
}

QColorBox::~QColorBox()
{
}

QColor QColorBox::color()
{
//return qVariantValue<QColor>(comboBox->itemData(comboBox->currentIndex(), Qt::BackgroundRole));
return comboBox->itemData(comboBox->currentIndex(), Qt::BackgroundRole).value<QColor>();
}

void QColorBox::setColor(const QColor& c)
{
int i;
int ind = -1;
QColor item_color;
for (i = 0; i < COLORTBL_SZ + 1; i++)
{
//item_color = qVariantValue<QColor>(comboBox->itemData(comboBox->currentIndex(), Qt::BackgroundRole));
item_color = (comboBox->itemData(comboBox->currentIndex(), Qt::BackgroundRole).value<QColor>());
if (item_color == c)
{
ind = i;
break;
}
}
if (ind >= 0)
comboBox->setCurrentIndex(ind);
else
{
setCustomColor(c);
comboBox->setCurrentIndex(COLORTBL_SZ + 1);
}
}

void QColorBox::setCustomColor(const QColor& c)
{
if (!c.isValid()) return;
customColor = c;
comboBox->setItemData(COLORTBL_SZ + 1, customColor, Qt::BackgroundRole);
comboBox->setItemData(COLORTBL_SZ + 1, customColor, Qt::DecorationRole);
if (comboBox->currentIndex() == COLORTBL_SZ + 1)
{
emit colorChanged(c);
comboBox->repaint();
}
}

void QColorBox::setDefaultColor(const QColor& c)
{
if (!c.isValid()) return;
defaultColor = c;
comboBox->setItemData(0, defaultColor, Qt::BackgroundRole);
comboBox->setItemData(0, defaultColor, Qt::DecorationRole);
if (comboBox->currentIndex() == 0)
{
emit colorChanged(c);
repaint();
}
}

void QColorBox::slotSelColor()
{
QColor sc = customColor;
sc = QColorDialog::getColor(sc, this);
if (sc.isValid())
{
//setCustomColor(sc);
//comboBox->setCurrentItem(COLORTBL_SZ + 1);
setColor(sc);
emit colorChanged(sc);
}
}

void QColorBox::slotChanged(int idx)
{
QColor c = comboBox->itemData(idx, Qt::BackgroundRole).value<QColor>();
emit colorChanged(c);
}

void QColorBox::languageChange()
{
comboBox->setItemText(0, tr("default"));
comboBox->setItemText(COLORTBL_SZ + 1, tr("custom"));
}
106 changes: 106 additions & 0 deletions src/colorbox.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/***************************************************************************
* Copyright (C) 2002-2019 by Chernov A.A. *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/

#ifndef COLORBOX_H
#define COLORBOX_H

#include <QtWidgets/QFrame>

class QHBoxLayout;
class QToolButton;

class QColorComboBox;

/**
\brief Элемент управления для выбора цвета.
Этот элемент управления позволяет выбирать различные цвета. Он состоит из двух компонентов:
QComboBox и QToolButton. Можно выбрать цвет из списка, или если нужного цвета нет, выбрать
цвет с помощью стандартного диалога выбора цвета, нажатием на кнопку QToolButton, при этом
выбранный цвет будет отображен в конце списка с пометкой "custom". Если пользователь не
выбирает цвет, то используется цвет "по умолчанию", представленый самым первым элементом списка
и задавемый функцией setDefaultColor(QColor& c). Всего в списке находится 16 цветов, с учётом
элементов "default" и "custom" всего в QComboBox 18 элементов.
\author Чернов А.А.
*/

class QColorBox : public QFrame
{
Q_OBJECT
public:
/**
* Конструктор.
* Создает элемент управления.
* \param parent родительский виджет, обязательно должен существовать;
*/
QColorBox(QWidget *parent);
/**
* Деструктор.
* Удаляет все внутренние переменные.
*/
~QColorBox();
/**
* Возвращает выбранный цвет.
*/
QColor color();
/**
* Устанавливает текущий выбранный цвет.
* Если этот цвет c найден в списке QComboBox, то выделяется соответствующий
* элемент списка, иначе устанавливается как дополнительный цвет. См. setCustomColor().
* \param c устанавливаемый цвет.
*/
void setColor(const QColor& c);
/**
* Устанавливает цвет по умолчанию. Это цвет находится в самом начале списка цветов.
* Таким образом, если пользователь не выбирает цвет в списке, то именно этот цвет
* возвращется функцией color().
* \param c устанавливаемый цвет.
*/
void setDefaultColor(const QColor& c);
signals:
/**
* Этот сигнал вызывается, когда изменяется значение цвета.
* Другими словами значения возвращаемые функцией color()
* до и после этого сигнала разные.
*/
void colorChanged(QColor);
protected:
/**
* Устанавливает дополнительный цвет. Этот цвет позднее может быть изменён
* пользователем. По умолчанию QColor(0, 0, 0).
* \param c устанавливаемый цвет.
*/
void setCustomColor(const QColor& c);
/**
* Для внутреннего использования. Заполняет список цветов.
*/
void fill();
protected slots:
virtual void languageChange();
void slotSelColor();
void slotChanged(int);
private:
QHBoxLayout* layout;
QColorComboBox* comboBox;
QToolButton* tool;
QColor defaultColor;
QColor customColor;
};

#endif
61 changes: 61 additions & 0 deletions src/colorbox_private.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/***************************************************************************
* Copyright (C) 2002-2019 by Chernov A.A. *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/

#include "colorbox_private.h"

#include <QtWidgets/QStylePainter>

#define MARGIN 6

QColorComboBox::QColorComboBox(QWidget* parent)
: QComboBox(parent)
{
}

QColorComboBox::~QColorComboBox()
{
}

void QColorComboBox::paintEvent(QPaintEvent*)
{
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));

// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);

// draw the icon and text
//painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
QString text = currentText();
QColor color = itemData(currentIndex(), Qt::BackgroundRole).value<QColor>();
QPen pen = painter.pen();
if (color.isValid())
{
QBrush brush(color, Qt::SolidPattern);
painter.setPen(Qt::NoPen);
painter.fillRect(opt.rect.left() + MARGIN, opt.rect.top() + MARGIN, opt.rect.width() - 2*MARGIN, opt.rect.height() - 2*MARGIN, brush);
}
pen.setColor(QColor(255 - color.red(), 255 - color.green(), 255 - color.blue()));
painter.setPen(pen);
QRect r = opt.rect;
r.setLeft(r.left() + MARGIN);
r.setWidth(r.width() - 2*MARGIN);
painter.drawText(r, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, text);
}
33 changes: 33 additions & 0 deletions src/colorbox_private.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/***************************************************************************
* Copyright (C) 2002-2019 by Chernov A.A. *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/

#ifndef COLORBOX_PRIVATE_H
#define COLORBOX_PRIVATE_H

#include <QtWidgets/QComboBox>

class QColorComboBox: public QComboBox
{
public:
QColorComboBox(QWidget* parent = 0);
~QColorComboBox();
protected:
virtual void paintEvent(QPaintEvent*);
};

#endif // COLORBOX_PRIVATE_H
Loading

0 comments on commit 5831765

Please sign in to comment.