AdvancedControllerRemoteCPP/panel/tabbar.cpp

103 lines
2.9 KiB
C++

// tabbar.cpp - CONTROLLER 1 / 2 / 3 tabs (see tabbar.h)
#include "tabbar.h"
#include "style.h"
#include <QMouseEvent>
#include <QPainter>
#include <algorithm>
namespace {
const int BarH = 46; // height of the bar
const int TabW = 200; // tab width (less when the window is narrow)
const int Gap = 10; // between the tabs
const int DotR = 7; // link dot radius
QColor dotColour(AdvCtrl::ControllerLink::State state)
{
switch (state) {
case AdvCtrl::ControllerLink::Link: return Style::Green;
case AdvCtrl::ControllerLink::NoLink: return Style::LedOn;
default: return Style::Grey;
}
}
} // namespace
TabBar::TabBar(int count, QWidget *parent)
: QWidget(parent)
{
for (int i = 0; i < count; ++i)
m_states.append(AdvCtrl::ControllerLink::Closed);
setFixedHeight(BarH);
}
void TabBar::setActive(int index)
{
m_active = index;
update();
}
void TabBar::setState(int index, AdvCtrl::ControllerLink::State state)
{
if (index < 0 || index >= m_states.size())
return;
m_states[index] = state;
update();
}
QRectF TabBar::tabRect(int index) const
{
const int n = int(m_states.size());
const double w = std::max(width(), 1);
const double tabW = std::min<double>(TabW, std::max(90.0, (w - (n - 1) * Gap) / n));
const double x = (w - (n * tabW + (n - 1) * Gap)) / 2;
return QRectF(x + index * (tabW + Gap), 4, tabW, BarH - 8);
}
void TabBar::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.fillRect(rect(), Style::Background);
QFont font(QStringLiteral("Arial"));
font.setStyleHint(QFont::SansSerif);
font.setBold(true);
font.setPointSize(11);
painter.setFont(font);
for (int i = 0; i < m_states.size(); ++i) {
const bool active = (i == m_active);
const QRectF r = tabRect(i);
painter.setPen(QPen(active ? Style::Line : Style::Grey, active ? 2 : 1));
painter.setBrush(active ? Style::TabActive : Style::Panel);
painter.drawRect(r);
if (active)
painter.fillRect(QRectF(r.left(), r.bottom() - 2, r.width(), 4), Style::Line);
const double cy = r.center().y();
painter.setPen(Qt::NoPen);
painter.setBrush(dotColour(m_states.at(i)));
painter.drawEllipse(QPointF(r.left() + 16 + DotR, cy), DotR, DotR);
painter.setPen(active ? QColor(Qt::white) : Style::Text);
const QRectF textRect(r.left() + 16 + 2 * DotR + 12, r.top(), r.width() - (16 + 2 * DotR + 12), r.height());
painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, QStringLiteral("CONTROLLER %1").arg(i + 1));
}
}
void TabBar::mousePressEvent(QMouseEvent *event)
{
if (event->button() != Qt::LeftButton)
return;
for (int i = 0; i < m_states.size(); ++i) {
if (tabRect(i).contains(event->position())) {
emit selected(i);
return;
}
}
}