#include <QApplication>
#include <QButtonGroup>
#include <QMouseEvent>
#include "xyzoomscroll.h"
#include "hotspotdialog.h"
#include <sstream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setStyleSheet("* {font-family:arial;font-size:11px}");
XYZoomScroll demo;
demo.show();
return app.exec();
}
XYZoomScroll::XYZoomScroll(QWidget *parent) :
QDialog(parent)
{
setWindowTitle("XY Zooming and Scrolling");
setFixedSize(644, 488);
QFrame *frame = new QFrame(this);
frame->setGeometry(4, 4, 120, 481);
frame->setFrameShape(QFrame::StyledPanel);
// Pointer push button
QPushButton *pointerPB = new QPushButton(QIcon(":/pointer.png"), "Pointer", frame);
pointerPB->setGeometry(4, 8, 112, 28);
pointerPB->setStyleSheet("QPushButton { text-align:left; padding:5px}");
pointerPB->setCheckable(true);
// Zoom In push button
QPushButton *zoomInPB = new QPushButton(QIcon(":/zoomin.png"), "Zoom In", frame);
zoomInPB->setGeometry(4, 36, 112, 28);
zoomInPB->setStyleSheet("QPushButton { text-align:left; padding:5px}");
zoomInPB->setCheckable(true);
// Zoom Out push button
QPushButton *zoomOutPB = new QPushButton(QIcon(":/zoomout.png"), "Zoom Out", frame);
zoomOutPB->setGeometry(4, 64, 112, 28);
zoomOutPB->setStyleSheet("QPushButton { text-align:left; padding:5px}");
zoomOutPB->setCheckable(true);
// The Pointer/Zoom In/Zoom Out buttons form a button group
QButtonGroup *mouseUsage = new QButtonGroup(frame);
mouseUsage->addButton(pointerPB, Chart::MouseUsageScroll);
mouseUsage->addButton(zoomInPB, Chart::MouseUsageZoomIn);
mouseUsage->addButton(zoomOutPB, Chart::MouseUsageZoomOut);
connect(mouseUsage, SIGNAL(buttonPressed(int)), SLOT(onMouseUsageChanged(int)));
// Zoom Mode label
QLabel *zoomModeLabel = new QLabel("Zoom Level", frame);
zoomModeLabel->setGeometry(6, 180, 110, 18);
zoomModeLabel->setAlignment(Qt::AlignHCenter);
// Zoom level bar
m_ZoomBar = new QSlider(Qt::Horizontal, frame);
m_ZoomBar->setGeometry(12, 205, 102, 41);
m_ZoomBar->setRange(1, 100);
m_ZoomBar->setTickPosition(QSlider::TicksBothSides);
m_ZoomBar->setInvertedAppearance(true);
connect(m_ZoomBar, SIGNAL(valueChanged(int)), SLOT(onZoomBarChanged(int)));
// The container of the draggable navigation window
m_NavigatePad = new QFrame(frame);
m_NavigatePad->setGeometry(4, 364, 113, 113);
m_NavigatePad->setFrameShape(QFrame::Panel);
m_NavigatePad->setFrameShadow(QFrame::Sunken);
// The dragging navigation window
m_NavigateWindow = new QDragRect(m_NavigatePad);
m_NavigateWindow->setGeometry(24, 28, 61, 53);
m_NavigateWindow->setAutoFillBackground(true);
m_NavigateWindow->setPalette(QPalette(QColor(0xc0, 0xc0, 0xff)));
m_NavigateWindow->setFrameShape(QFrame::Box);
m_NavigateWindow->setFrameShadow(QFrame::Plain);
connect(m_NavigateWindow, SIGNAL(mouseDrag(QPoint, QPoint)),
SLOT(onNavigateWindowDrag(QPoint, QPoint)));
// Chart Viewer
m_ChartViewer = new QChartViewer(this);
m_ChartViewer->setGeometry(QRect(136, 4, 500, 480));
connect(m_ChartViewer, SIGNAL(viewPortChanged()), SLOT(onViewPortChanged()));
connect(m_ChartViewer, SIGNAL(mouseMovePlotArea(QMouseEvent*)), SLOT(onMouseMovePlotArea(QMouseEvent*)));
connect(m_ChartViewer, SIGNAL(mouseWheel(QWheelEvent*)), SLOT(onMouseWheelChart(QWheelEvent*)));
connect(m_ChartViewer, SIGNAL(clicked(QMouseEvent*)), SLOT(onClickChart(QMouseEvent*)));
//
// Initialize member variables
//
// Set initial zoom/scroll direction
m_ChartViewer->setScrollDirection(Chart::DirectionHorizontalVertical);
m_ChartViewer->setZoomDirection(Chart::DirectionHorizontalVertical);
// Initially set the mouse to drag to scroll mode
pointerPB->click();
// Can update chart now
m_ChartViewer->updateViewPort(true, true);
}
XYZoomScroll::~XYZoomScroll()
{
delete m_ChartViewer->getChart();
}
//
// The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in or
// out the chart by dragging or clicking on the chart. It can also be triggered by calling
// QChartViewer.updateViewPort.
//
void XYZoomScroll::onViewPortChanged()
{
// In addition to updating the chart, we may also need to update other controls that
// changes based on the view port.
updateControls(m_ChartViewer);
//
// Update chart and image map if necessary
//
if (m_ChartViewer->needUpdateChart())
drawChart(m_ChartViewer);
if (m_ChartViewer->needUpdateImageMap())
updateImageMap(m_ChartViewer);
// We need to update the track line too. If the mouse is moving on the chart (eg. if
// the user drags the mouse on the chart to scroll it), the track line will be updated
// in the MouseMovePlotArea event. Otherwise, we need to update the track line here.
if ((!m_ChartViewer->isInMouseMoveEvent()) && m_ChartViewer->isMouseOnPlotArea())
{
crossHair((XYChart *)m_ChartViewer->getChart(), m_ChartViewer->getPlotAreaMouseX(),
m_ChartViewer->getPlotAreaMouseY());
m_ChartViewer->updateDisplay();
}
}
//
// Update controls when the view port changed
//
void XYZoomScroll::updateControls(QChartViewer *viewer)
{
//
// Update the Zoom slider to reflect the current zoom level of the view port
//
double smallerSide = viewer->getViewPortWidth() > viewer->getViewPortHeight()
? viewer->getViewPortHeight() : viewer->getViewPortWidth();
m_ZoomBar->setValue((int)(smallerSide * m_ZoomBar->maximum() + 0.5));
//
// Update the navigate window to reflect the current view port position and size. (Note:
// we allowed for a 2-pixel margin for the frame border in the following computations.)
//
int borderWidth = m_NavigatePad->frameWidth();
int left = (int)(viewer->getViewPortLeft() * (m_NavigatePad->width() - borderWidth * 2) + borderWidth + 0.5);
int top = (int)(viewer->getViewPortTop() * (m_NavigatePad->height() - borderWidth * 2) + borderWidth + 0.5);
int width = (int)(viewer->getViewPortWidth() * (m_NavigatePad->width() - borderWidth * 2) + 0.5);
int height = (int)(viewer->getViewPortHeight() * (m_NavigatePad->height() - borderWidth * 2) + 0.5);
m_NavigateWindow->setGeometry(left, top, width, height);
}
//
// Draw the chart and display it in the given viewer
//
void XYZoomScroll::drawChart(QChartViewer *viewer)
{
//
// For simplicity, in this demo, we just use hard coded data. In a real application,
// the data probably read from a dynamic source such as a database. (See the
// ChartDirector documentation on "Using Data Sources with ChartDirector" if you need
// some sample code on how to read data from database to array variables.)
//
double dataX0[] = {10, 15, 6, -12, 14, -8, 13, -3, 16, 12, 10.5, -7, 3, -10, -5, 2, 5};
double dataY0[] = {130, 150, 80, 110, -110, -105, -130, -15, -170, 125, 125, 60, 25, 150,
150,15, 120};
double dataX1[] = {6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8, -3, -2, 8, 4, -15, 15};
double dataY1[] = {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60, 50, 20, 170, -25,
50, 75};
double dataX2[] = {-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9, 3, -13, 16, -7.5, -10, -15};
double dataY2[] = {65, -80, -40, 45, -70, -80, 80, 90, -100, 105, 60, -75, -150, -40, 120,
-50, -30};
// Create an XYChart object 500 x 480 pixels in size, with the same background color
// as the container
QColor bgColor = palette().color(backgroundRole()).rgb();
XYChart *c = new XYChart(500, 480, (bgColor.red() << 16) + (bgColor.green() << 8) + bgColor.blue());
// Set the plotarea at (50, 40) and of size 400 x 400 pixels. Use light grey (c0c0c0)
// horizontal and vertical grid lines. Set 4 quadrant coloring, where the colors of
// the quadrants alternate between lighter and deeper grey (dddddd/eeeeee).
c->setPlotArea(50, 40, 400, 400, -1, -1, -1, 0xc0c0c0, 0xc0c0c0
)->set4QBgColor(0xdddddd, 0xeeeeee, 0xdddddd, 0xeeeeee, 0x000000);
// Enable clipping mode to clip the part of the data that is outside the plot area.
c->setClipping();
// Set 4 quadrant mode, with both x and y axes symetrical around the origin
c->setAxisAtOrigin(Chart::XYAxisAtOrigin, Chart::XAxisSymmetric + Chart::YAxisSymmetric);
// Add a legend box at (450, 40) (top right corner of the chart) with vertical layout
// and 8 pts Arial Bold font. Set the background color to semi-transparent grey.
LegendBox *legendBox = c->addLegend(450, 40, true, "arialbd.ttf", 8);
legendBox->setAlignment(Chart::TopRight);
legendBox->setBackground(0x40dddddd);
// Add a titles to axes
c->xAxis()->setTitle("Alpha Index");
c->yAxis()->setTitle("Beta Index");
// Set axes width to 2 pixels
c->xAxis()->setWidth(2);
c->yAxis()->setWidth(2);
// The default ChartDirector settings has a denser y-axis grid spacing and less-dense
// x-axis grid spacing. In this demo, we want the tick spacing to be symmetrical.
// We use around 50 pixels between major ticks and 25 pixels between minor ticks.
c->xAxis()->setTickDensity(50, 25);
c->yAxis()->setTickDensity(50, 25);
//
// In this example, we represent the data by scatter points. If you want to represent
// the data by somethings else (lines, bars, areas, floating boxes, etc), just modify
// the code below to use the layer type of your choice.
//
// Add scatter layer, using 11 pixels red (ff33333) X shape symbols
c->addScatterLayer(DoubleArray(dataX0, sizeof(dataX0) / sizeof(dataX0[0])),
DoubleArray(dataY0, sizeof(dataY0) / sizeof(dataY0[0])), "Group A",
Chart::Cross2Shape(), 11, 0xff3333);
// Add scatter layer, using 11 pixels green (33ff33) circle symbols
c->addScatterLayer(DoubleArray(dataX1, sizeof(dataX1) / sizeof(dataX1[0])),
DoubleArray(dataY1, sizeof(dataY1) / sizeof(dataY1[0])),
"Group B", Chart::CircleShape, 11, 0x33ff33);
// Add scatter layer, using 11 pixels blue (3333ff) triangle symbols
c->addScatterLayer(DoubleArray(dataX2, sizeof(dataX2) / sizeof(dataX2[0])),
DoubleArray(dataY2, sizeof(dataY2) / sizeof(dataY2[0])),
"Group C", Chart::TriangleSymbol, 11, 0x3333ff);
//
// In this example, we have not explicitly configured the full x and y range. In this case,
// the first time syncLinearAxisWithViewPort is called, ChartDirector will auto-scale the axis
// and assume the resulting range is the full range. In subsequent calls, ChartDirector will
// set the axis range based on the view port and the full range.
//
viewer->syncLinearAxisWithViewPort("x", c->xAxis());
viewer->syncLinearAxisWithViewPort("y", c->yAxis());
// Set the chart image to the QChartViewer
delete viewer->getChart();
viewer->setChart(c);
}
//
// Update the image map
//
void XYZoomScroll::updateImageMap(QChartViewer *viewer)
{
if (0 == viewer->getImageMapHandler())
{
// no existing image map - creates a new one
viewer->setImageMap(viewer->getChart()->getHTMLImageMap("clickable", "",
"title='[{dataSetName}] Alpha = {x}, Beta = {value}'"));
}
}
//
// User clicks on the QChartViewer
//
void XYZoomScroll::onClickChart(QMouseEvent *)
{
ImageMapHandler *handler = m_ChartViewer->getImageMapHandler();
if (0 != handler)
{
// Query the ImageMapHandler to see if the mouse is on a clickable hot spot. We
// consider the hot spot as clickable if its href ("path") parameter is not empty.
const char *path = handler->getValue("path");
if ((0 != path) && (0 != *path))
{
// In this sample code, we just show all hot spot parameters.
HotSpotDialog hs;
hs.setData(handler);
hs.exec();
}
}
}
//
// The Pointer, Zoom In or Zoom out button is pressed
//
void XYZoomScroll::onMouseUsageChanged(int mouseUsage)
{
m_ChartViewer->setMouseUsage(mouseUsage);
}
//
// User moves the Zoom slider control
//
void XYZoomScroll::onZoomBarChanged(int value)
{
if (!m_ChartViewer->isInViewPortChangedEvent())
{
// Remember the center point
double centerX = m_ChartViewer->getViewPortLeft() +
m_ChartViewer->getViewPortWidth() / 2;
double centerY = m_ChartViewer->getViewPortTop() +
m_ChartViewer->getViewPortHeight() / 2;
// Aspect ratio and zoom factor
double aspectRatio = m_ChartViewer->getViewPortWidth() /
m_ChartViewer->getViewPortHeight();
double zoomTo = ((double)value) / m_ZoomBar->maximum();
// Zoom by adjusting ViewPortWidth and ViewPortHeight while maintaining the aspect ratio
m_ChartViewer->setViewPortWidth(zoomTo * ((aspectRatio < 1) ? 1 : aspectRatio));
m_ChartViewer->setViewPortHeight(zoomTo * ((aspectRatio > 1) ? 1 : (1 / aspectRatio)));
// Adjust ViewPortLeft and ViewPortTop to keep center point unchanged
m_ChartViewer->setViewPortLeft(centerX - m_ChartViewer->getViewPortWidth() / 2);
m_ChartViewer->setViewPortTop(centerY - m_ChartViewer->getViewPortHeight() / 2);
// Update the chart image only, but no need to update the image map.
m_ChartViewer->updateViewPort(true, false);
}
}
//
// Scroll the chart when the user drags the navigate window
//
void XYZoomScroll::onNavigateWindowDrag(QPoint fromPoint, QPoint toPoint)
{
//
// Get the position of the navigate window inside the navigate pad as a ratio between 0 - 1.
//
double viewPortLeft = ((double)m_NavigateWindow->x() + toPoint.x() - fromPoint.x() -
m_NavigatePad->frameWidth()) / (m_NavigatePad->width() - m_NavigatePad->frameWidth() * 2);
double viewPortTop = ((double)m_NavigateWindow->y() + toPoint.y() - fromPoint.y() -
m_NavigatePad->frameWidth()) / (m_NavigatePad->height() - m_NavigatePad->frameWidth() * 2);
scrollChartTo(viewPortLeft, viewPortTop);
}
//
// Scroll the view port to the given position if necessary
//
void XYZoomScroll::scrollChartTo(double viewPortLeft, double viewPortTop)
{
//
// Ensures the view port is within valid range.
//
viewPortLeft = max(0.0, min(viewPortLeft, 1 - m_ChartViewer->getViewPortWidth()));
viewPortTop = max(0.0, min(viewPortTop, 1 - m_ChartViewer->getViewPortHeight()));
//
// Update chart only if the view port has actually changed
//
if ((viewPortLeft != m_ChartViewer->getViewPortLeft()) ||
(viewPortTop != m_ChartViewer->getViewPortTop()))
{
m_ChartViewer->setViewPortLeft(viewPortLeft);
m_ChartViewer->setViewPortTop(viewPortTop);
// Update the chart image only, but no need to update the image map.
m_ChartViewer->updateViewPort(true, false);
}
}
//
// When the mouse enters the chart, we will generate an image map for hot spots and tooltips
// support if it has not already been generated.
//
void XYZoomScroll::onMouseWheelChart(QWheelEvent *event)
{
// Process the mouse wheel only if the mouse is over the plot area
if (!m_ChartViewer->isMouseOnPlotArea())
{
event->ignore();
return;
}
// We zoom in or out by 10% depending on the mouse wheel direction.
double newVpWidth = m_ChartViewer->getViewPortWidth() * (event->delta() > 0 ? 0.9 : 1 / 0.9);
double newVpHeight = m_ChartViewer->getViewPortHeight() * (event->delta() > 0 ? 0.9 : 1 / 0.9);
// We do not zoom beyond the zoom width or height limits.
newVpWidth = max(m_ChartViewer->getZoomInWidthLimit(), min(newVpWidth,
m_ChartViewer->getZoomOutWidthLimit()));
newVpHeight = max(m_ChartViewer->getZoomInHeightLimit(), min(newVpWidth,
m_ChartViewer->getZoomOutHeightLimit()));
if ((newVpWidth != m_ChartViewer->getViewPortWidth()) ||
(newVpHeight != m_ChartViewer->getViewPortHeight()))
{
// Set the view port position and size so that the point under the mouse remains under
// the mouse after zooming.
double deltaX = (m_ChartViewer->getPlotAreaMouseX() - m_ChartViewer->getPlotAreaLeft()) *
(m_ChartViewer->getViewPortWidth() - newVpWidth) / m_ChartViewer->getPlotAreaWidth();
m_ChartViewer->setViewPortLeft(m_ChartViewer->getViewPortLeft() + deltaX);
m_ChartViewer->setViewPortWidth(newVpWidth);
double deltaY = (m_ChartViewer->getPlotAreaMouseY() - m_ChartViewer->getPlotAreaTop()) *
(m_ChartViewer->getViewPortHeight() - newVpHeight) / m_ChartViewer->getPlotAreaHeight();
m_ChartViewer->setViewPortTop(m_ChartViewer->getViewPortTop() + deltaY);
m_ChartViewer->setViewPortHeight(newVpHeight);
m_ChartViewer->updateViewPort(true, false);
}
}
//
// Draw track cursor when mouse is moving over plotarea, and update image map if necessary
//
void XYZoomScroll::onMouseMovePlotArea(QMouseEvent *)
{
// Draw crosshair track cursor
crossHair((XYChart *)m_ChartViewer->getChart(), m_ChartViewer->getPlotAreaMouseX(),
m_ChartViewer->getPlotAreaMouseY());
m_ChartViewer->updateDisplay();
// Hide the track cursor when the mouse leaves the plot area
m_ChartViewer->removeDynamicLayer("mouseLeavePlotArea");
// Update image map if necessary
updateImageMap(m_ChartViewer);
}
//
// Draw cross hair cursor with axis labels
//
void XYZoomScroll::crossHair(XYChart *c, int mouseX, int mouseY)
{
// Clear the current dynamic layer and get the DrawArea object to draw on it.
DrawArea *d = c->initDynamicLayer();
// The plot area object
PlotArea *plotArea = c->getPlotArea();
// Draw a vertical line and a horizontal line as the cross hair
d->vline(plotArea->getTopY(), plotArea->getBottomY(), mouseX, d->dashLineColor(0x000000, 0x0101));
d->hline(plotArea->getLeftX(), plotArea->getRightX(), mouseY, d->dashLineColor(0x000000, 0x0101));
// Draw y-axis label
ostringstream ylabel;
ylabel << "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" << c->formatValue(c->getYValue(
mouseY, c->yAxis()), "{value|P4}") << "<*/*>";
TTFText *t = d->text(ylabel.str().c_str(), "arialbd.ttf", 8);
t->draw(plotArea->getLeftX() - 5, mouseY, 0x000000, Chart::Right);
t->destroy();
// Draw x-axis label
ostringstream xlabel;
xlabel << "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" << c->formatValue(c->getXValue(
mouseX), "{value|P4}") << "<*/*>";
t = d->text(xlabel.str().c_str(), "arialbd.ttf", 8);
t->draw(mouseX, plotArea->getBottomY() + 5, 0x000000, Chart::Top);
t->destroy();
} |