Add table of layout of details.

master
dismine 2013-08-29 13:31:50 +03:00
parent 51a17f453d
commit ebf803122e
40 changed files with 1282 additions and 124 deletions

View File

@ -4,9 +4,7 @@
#
#-------------------------------------------------
QT += core gui xml
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
QT += core gui widgets xml svg printsupport
TARGET = Valentina
TEMPLATE = app
@ -68,7 +66,10 @@ SOURCES += main.cpp\
tools/vmodelingpoint.cpp \
tools/vmodelingspline.cpp \
tools/vmodelingarc.cpp \
tools/vmodelingsplinepath.cpp
tools/vmodelingsplinepath.cpp \
widgets/vtablegraphicsview.cpp \
widgets/vitem.cpp \
tablewindow.cpp
HEADERS += mainwindow.h \
widgets/vmaingraphicsscene.h \
@ -127,7 +128,10 @@ HEADERS += mainwindow.h \
tools/vmodelingpoint.h \
tools/vmodelingspline.h \
tools/vmodelingarc.h \
tools/vmodelingsplinepath.h
tools/vmodelingsplinepath.h \
widgets/vtablegraphicsview.h \
widgets/vitem.h \
tablewindow.h
FORMS += mainwindow.ui \
dialogs/dialogsinglepoint.ui \
@ -144,7 +148,8 @@ FORMS += mainwindow.ui \
dialogs/dialogsplinepath.ui \
dialogs/dialoghistory.ui \
dialogs/dialogpointofcontact.ui \
dialogs/dialogdetail.ui
dialogs/dialogdetail.ui \
tablewindow.ui
RESOURCES += \
icon.qrc \

View File

@ -29,6 +29,18 @@ const VContainer &VContainer::operator =(const VContainer &data){
return *this;
}
VContainer::VContainer(const VContainer &data):base(QMap<QString, qint32>()), points(QMap<qint64, VPointF>()),
modelingPoints(QMap<qint64, VPointF>()),
standartTable(QMap<QString, VStandartTableCell>()), incrementTable(QMap<QString, VIncrementTableRow>()),
lengthLines(QMap<QString, qreal>()), lineAngles(QMap<QString, qreal>()), splines(QMap<qint64, VSpline>()),
modelingSplines(QMap<qint64, VSpline>()),
lengthSplines(QMap<QString, qreal>()), arcs(QMap<qint64, VArc>()), modelingArcs(QMap<qint64, VArc>()),
lengthArcs(QMap<QString, qreal>()),
splinePaths(QMap<qint64, VSplinePath>()), modelingSplinePaths(QMap<qint64, VSplinePath>()),
details(QMap<qint64, VDetail>()){
setData(data);
}
void VContainer::setData(const VContainer &data){
base = *data.DataBase();
points = *data.DataPoints();
@ -169,6 +181,52 @@ void VContainer::IncrementReferens(qint64 id, Scene::Type obj){
}
}
QPainterPath VContainer::ContourPath(qint64 idDetail) const{
VDetail detail = GetDetail(idDetail);
QVector<QPointF> points;
for(qint32 i = 0; i< detail.CountNode(); ++i){
switch(detail[i].getTypeTool()){
case(Scene::Line):
break;
case(Scene::Point):{
VPointF point = GetModelingPoint(detail[i].getId());
points.append(point.toQPointF());
}
break;
case(Scene::Arc):{
VArc arc = GetModelingArc(detail[i].getId());
points << arc.GetPoints();
}
break;
case(Scene::Spline):{
VSpline spline = GetModelingSpline(detail[i].getId());
points << spline.GetPoints();
}
break;
case(Scene::SplinePath):{
VSplinePath splinePath = GetModelingSplinePath(detail[i].getId());
points << splinePath.GetPathPoints();
}
break;
}
}
QPainterPath path;
path.moveTo(points[0]);
for (qint32 i = 1; i < points.count(); ++i){
path.lineTo(points[i]);
}
path.lineTo(points[0]);
return path;
}
void VContainer::PrepareDetails(QVector<VItem *> &list) const{
QMapIterator<qint64, VDetail> iDetail(details);
while (iDetail.hasNext()) {
iDetail.next();
list.append(new VItem(ContourPath(iDetail.key()), list.size()));
}
}
void VContainer::RemoveIncrementTableRow(const QString& name){
incrementTable.remove(name);
}

View File

@ -17,6 +17,7 @@
#include "../geometry/varc.h"
#include "../geometry/vsplinepath.h"
#include "../geometry/vdetail.h"
#include "../widgets/vitem.h"
/**
* @brief The VContainer class
@ -29,6 +30,7 @@ public:
*/
VContainer();
const VContainer &operator=(const VContainer &data);
VContainer(const VContainer &data);
void setData(const VContainer &data);
/**
* @brief GetPoint
@ -118,6 +120,8 @@ public:
const QMap<qint64, VDetail> *DataDetails() const;
void UpdateId(qint64 newId);
void IncrementReferens(qint64 id, Scene::Type obj);
QPainterPath ContourPath(qint64 idDetail) const;
void PrepareDetails(QVector<VItem*> & list)const;
private:
static qint64 _id;
QMap<QString, qint32> base;

View File

@ -27,32 +27,26 @@ VNodeDetail &VDetail::operator [](int indx){
return nodes[indx];
}
qreal VDetail::getMy() const
{
qreal VDetail::getMy() const{
return my;
}
void VDetail::setMy(const qreal &value)
{
void VDetail::setMy(const qreal &value){
my = value;
}
qreal VDetail::getMx() const
{
qreal VDetail::getMx() const{
return mx;
}
void VDetail::setMx(const qreal &value)
{
void VDetail::setMx(const qreal &value){
mx = value;
}
QString VDetail::getName() const
{
QString VDetail::getName() const{
return name;
}
void VDetail::setName(const QString &value)
{
void VDetail::setName(const QString &value){
name = value;
}

View File

@ -4,6 +4,7 @@
#include "vnodedetail.h"
#include <QVector>
#include <QString>
#include <QPainterPath>
class VDetail
{

View File

@ -32,5 +32,7 @@
<file>icon/32x32/put_after.png</file>
<file>icon/32x32/point_of_contact.png</file>
<file>icon/32x32/new_detail.png</file>
<file>icon/32x32/layout.png</file>
<file>icon/16x16/mirror.png</file>
</qresource>
</RCC>

BIN
icon/16x16/mirror.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 454 B

BIN
icon/32x32/layout.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -1,9 +1,7 @@
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#include "mainwindow.h"
#include <QApplication>
#include <QTextCodec>
#pragma GCC diagnostic pop
#include "tablewindow.h"
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg){
QByteArray localMsg = msg.toLocal8Bit();
@ -32,6 +30,9 @@ int main(int argc, char *argv[]){
QApplication app(argc, argv);
MainWindow w;
app.setWindowIcon(QIcon(":/icon/64x64/icon64x64.png"));
TableWindow table;
QObject::connect(&w, &MainWindow::ModelChosen, &table, &TableWindow::ModelChosen);
QObject::connect(&table, &TableWindow::closed, &w, &MainWindow::tableClosed);
w.show();
return app.exec();

View File

@ -69,7 +69,6 @@ MainWindow::MainWindow(QWidget *parent) :
connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::ActionOpen);
connect(ui->actionNew, &QAction::triggered, this, &MainWindow::ActionNew);
connect(ui->actionTable, &QAction::triggered, this, &MainWindow::ActionTable);
connect(ui->actionHistory, &QAction::triggered, this, &MainWindow::ActionHistory);
connect(ui->toolButtonEndLine, &QToolButton::clicked, this, &MainWindow::ToolEndLine);
connect(ui->toolButtonLine, &QToolButton::clicked, this, &MainWindow::ToolLine);
connect(ui->toolButtonAlongLine, &QToolButton::clicked, this, &MainWindow::ToolAlongLine);
@ -85,7 +84,7 @@ MainWindow::MainWindow(QWidget *parent) :
data = new VContainer;
doc = new VDomDocument(data, comboBoxDraws);
doc = new VDomDocument(data, comboBoxDraws, &mode);
doc->CreateEmptyFile();
connect(doc, &VDomDocument::haveChange, this, &MainWindow::haveChange);
@ -364,6 +363,11 @@ void MainWindow::ClosedDialogDetail(int result){
ArrowTool();
}
void MainWindow::tableClosed(){
show();
MinimumScrollBar();
}
void MainWindow::showEvent( QShowEvent *event ){
QMainWindow::showEvent( event );
if( event->spontaneous() ){
@ -374,10 +378,7 @@ void MainWindow::showEvent( QShowEvent *event ){
return;
}
// do your init stuff here
QScrollBar *horScrollBar = view->horizontalScrollBar();
horScrollBar->setValue(horScrollBar->minimum());
QScrollBar *verScrollBar = view->verticalScrollBar();
verScrollBar->setValue(verScrollBar->minimum());
MinimumScrollBar();
isInitialized = true;//перший показ вікна вже відбувся
}
@ -441,6 +442,10 @@ void MainWindow::ToolBarDraws(){
ui->toolBarDraws->addAction(ui->actionHistory);
ui->actionHistory->setEnabled(false);
connect(ui->actionHistory, &QAction::triggered, this, &MainWindow::ActionHistory);
ui->toolBarDraws->addAction(ui->actionLayout);
connect(ui->actionLayout, &QAction::triggered, this, &MainWindow::ActionLayout);
}
void MainWindow::currentDrawChanged( int index ){
@ -567,6 +572,7 @@ void MainWindow::ActionDraw(bool checked){
currentScene = sceneDraw;
view->setScene(currentScene);
mode = Draw::Calculation;
doc->setCurrentData();
} else {
ui->actionDraw->setChecked(true);
}
@ -735,6 +741,14 @@ void MainWindow::ActionHistory(bool checked){
}
}
void MainWindow::ActionLayout(bool checked){
Q_UNUSED(checked);
hide();
QVector<VItem*> listDetails;
data->PrepareDetails(listDetails);
emit ModelChosen(listDetails);
}
void MainWindow::ClosedActionHistory(){
ui->actionHistory->setChecked(false);
delete dialogHistory;
@ -755,6 +769,13 @@ void MainWindow::SetEnableTool(bool enable){
ui->toolButtonNewDetail->setEnabled(enable);
}
void MainWindow::MinimumScrollBar(){
QScrollBar *horScrollBar = view->horizontalScrollBar();
horScrollBar->setValue(horScrollBar->minimum());
QScrollBar *verScrollBar = view->verticalScrollBar();
verScrollBar->setValue(verScrollBar->minimum());
}
MainWindow::~MainWindow(){
CanselTool();
delete ui;

View File

@ -35,6 +35,7 @@
#pragma GCC diagnostic pop
#include "container/vcontainer.h"
#include "options.h"
#include "widgets/vitem.h"
namespace Ui {
class MainWindow;
@ -64,6 +65,7 @@ public slots:
void ActionTable(bool checked);
void ClosedActionTable();
void ActionHistory(bool checked);
void ActionLayout(bool checked);
void ClosedActionHistory();
void ToolEndLine(bool checked);
void ClosedDialogEndLine(int result);
@ -89,6 +91,17 @@ public slots:
void ClosedDialogPointOfContact(int result);
void ToolDetail(bool checked);
void ClosedDialogDetail(int result);
/**
* @brief tableClosed Слот, що виконується при отриманні сигналу закриття вікна укладання
*деталей моделі.
*/
void tableClosed();
signals:
/**
* @brief ModelChosen Сигнал, що висилається після розрахунку всіх деталей моделі.
* @param listDetails Список детайле моделі.
*/
void ModelChosen(QVector<VItem*> listDetails);
protected:
virtual void keyPressEvent ( QKeyEvent * event );
virtual void showEvent( QShowEvent *event );
@ -132,7 +145,8 @@ private:
void SetEnableTool(bool enable);
template <typename Dialog, typename Func>
void SetToolButton(bool checked, Tools::Enum t, const QString &cursor, QSharedPointer<Dialog> &dialog,
Func closeDialogSlot);
Func closeDialogSlot);
void MinimumScrollBar();
};
#endif // MAINWINDOW_H

View File

@ -37,7 +37,7 @@
<rect>
<x>0</x>
<y>0</y>
<width>150</width>
<width>144</width>
<height>104</height>
</rect>
</property>
@ -641,6 +641,15 @@
<string>History</string>
</property>
</action>
<action name="actionLayout">
<property name="icon">
<iconset resource="icon.qrc">
<normaloff>:/icon/32x32/layout.png</normaloff>:/icon/32x32/layout.png</iconset>
</property>
<property name="text">
<string>Розкладка</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources>

354
tablewindow.cpp Normal file
View File

@ -0,0 +1,354 @@
#include "tablewindow.h"
#include "ui_tablewindow.h"
#include <QCloseEvent>
#include <QDesktopWidget>
#include "widgets/vtablegraphicsview.h"
#include <QFileDialog>
#include "options.h"
#include <QtSvg/QtSvg>
#undef PaperSize
#include <QtPrintSupport/QPrinter>
TableWindow::TableWindow(QWidget *parent) :
QMainWindow(parent), numberDetal(0), colission(0), ui(new Ui::TableWindow),
listDetails(QVector<VItem*>()), outItems(false), collidingItems(false), currentScene(0),
paper(0), shadowPaper(0), listOutItems(0), listCollidingItems(QList<QGraphicsItem*>()),
indexDetail(0), sceneRect(QRectF()){
ui->setupUi(this);
numberDetal = new QLabel("Залишилось 0 деталей.", this);
colission = new QLabel("Колізій не знайдено.", this);
ui->statusBar->addWidget(numberDetal);
ui->statusBar->addWidget(colission);
outItems = collidingItems = false;
//sceneRect = QRectF(0, 0, 203*PrintDPI/25.4, 287*PrintDPI/25.4);
sceneRect = QRectF(0, 0, toPixel(823), toPixel(1171));
currentScene = new QGraphicsScene(sceneRect);
QBrush *brush = new QBrush();
brush->setStyle( Qt::SolidPattern );
brush->setColor( QColor( Qt::gray ) );
currentScene->setBackgroundBrush( *brush );
VTableGraphicsView* view = new VTableGraphicsView(currentScene);
view->fitInView(view->scene()->sceneRect(),Qt::KeepAspectRatio);
ui->horizontalLayout->addWidget(view);
connect(ui->actionTurn, &QAction::triggered, view, &VTableGraphicsView::rotateItems);
connect(ui->actionMirror, &QAction::triggered, view, &VTableGraphicsView::MirrorItem);
connect(ui->actionZoomIn, &QAction::triggered, view, &VTableGraphicsView::ZoomIn);
connect(ui->actionZoomOut, &QAction::triggered, view, &VTableGraphicsView::ZoomOut);
connect(ui->actionStop, &QAction::triggered, this, &TableWindow::StopTable);
connect(ui->actionSave, &QAction::triggered, this, &TableWindow::saveScene);
connect(ui->actionNext, &QAction::triggered, this, &TableWindow::GetNextDetail);
connect(ui->actionAdd, &QAction::triggered, this, &TableWindow::AddLength);
connect(ui->actionRemove, &QAction::triggered, this, &TableWindow::RemoveLength);
connect(view, &VTableGraphicsView::itemChect, this, &TableWindow::itemChect);
}
TableWindow::~TableWindow(){
delete ui;
}
void TableWindow::AddPaper(){
qreal x1, y1, x2, y2;
sceneRect.getCoords(&x1, &y1, &x2, &y2);
shadowPaper = new QGraphicsRectItem(QRectF(x1+4,y1+4,x2+4, y2+4));
shadowPaper->setBrush(QBrush(Qt::black));
currentScene->addItem(shadowPaper);
paper = new QGraphicsRectItem(QRectF(x1,y1,x2, y2));
paper->setPen(QPen(Qt::black, toPixel(widthMainLine)));
paper->setBrush(QBrush(Qt::white));
currentScene->addItem(paper);
qDebug()<<paper->rect().size().toSize();
}
void TableWindow::AddDetail(){
if(indexDetail<listDetails.count()){
currentScene->clearSelection();
VItem* Detail = listDetails[indexDetail];
QObject::connect(Detail, SIGNAL(itemOut(int,bool)), this, SLOT(itemOut(int,bool)));
QObject::connect(Detail, SIGNAL(itemColliding(QList<QGraphicsItem*>,int)), this,
SLOT(itemColliding(QList<QGraphicsItem*>,int)));
QObject::connect(this, SIGNAL(LengthChanged()), Detail, SLOT(LengthChanged()));
Detail->setPen(QPen(Qt::black, toPixel(widthMainLine)));
Detail->setBrush(QBrush(Qt::white));
Detail->setPos(paper->boundingRect().center());
Detail->setFlag(QGraphicsItem::ItemIsMovable, true);
Detail->setFlag(QGraphicsItem::ItemIsSelectable, true);
Detail->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
Detail->setParentItem(paper);
Detail->setSelected(true);
indexDetail++;
if(indexDetail==listDetails.count()){
ui->actionSave->setEnabled(true);
}
}
numberDetal->setText(QString("Залишилось %1 деталей.").arg(listDetails.count()-indexDetail));
}
/*
* Отримуємо деталі розрахованої моделі для подальшого укладання.
*/
void TableWindow::ModelChosen(QVector<VItem*> listDetails){
this->listDetails = listDetails;
listOutItems = new QBitArray(this->listDetails.count());
AddPaper();
indexDetail = 0;
AddDetail();
show();
}
void TableWindow::closeEvent(QCloseEvent *event){
event->ignore();
StopTable();
}
void TableWindow::moveToCenter(){
QRect rect = frameGeometry();
rect.moveCenter(QDesktopWidget().availableGeometry().center());
move(rect.topLeft());
}
void TableWindow::showEvent ( QShowEvent * event ){
QMainWindow::showEvent(event);
moveToCenter();
}
void TableWindow::StopTable(){
hide();
currentScene->clear();
delete listOutItems;
listDetails.clear();
//sceneRect = QRectF(0, 0, 230*resol/25.9, 327*resol/25.9);
sceneRect = QRectF(0, 0, toPixel(823), toPixel(1171));
emit closed();
}
void TableWindow::saveScene(){
QString name = QFileDialog::getSaveFileName(0, "Зберегти розкладку", "", "Images (*.png);;Svg files (*.svg);;Ps files (*.ps)");
if(name.isNull()){
return;
}
QBrush *brush = new QBrush();
brush->setColor( QColor( Qt::white ) );
currentScene->setBackgroundBrush( *brush );
currentScene->clearSelection(); // Selections would also render to the file
shadowPaper->setBrush(QBrush(Qt::white));
shadowPaper->setPen(QPen(Qt::white, 0.1));
paper->setPen(QPen(Qt::white, 0.1));
paper->setBrush(QBrush(Qt::white));
currentScene->setSceneRect(QRectF(10,10,590,590));
currentScene->setSceneRect(currentScene->itemsBoundingRect());
QFileInfo fi(name);
if(fi.suffix() == "svg"){
SvgFile(name);
} else if(fi.suffix() == "png"){
PngFile(name);
} else if(fi.suffix() == "ps"){
PsFile(name);
}
// if(name.indexOf(".svg",name.size()-4)<0){
// name.append(".svg");
// }
brush->setColor( QColor( Qt::gray ) );
brush->setStyle( Qt::SolidPattern );
currentScene->setBackgroundBrush( *brush );
paper->setPen(QPen(Qt::black, widthMainLine));
shadowPaper->setBrush(QBrush(Qt::black));
}
void TableWindow::itemChect(bool flag){
ui->actionTurn->setDisabled(flag);
ui->actionMirror->setDisabled(flag);
}
void TableWindow::checkNext(){
if(outItems == true && collidingItems == true){
colission->setText("Колізій не знайдено.");
if(indexDetail==listDetails.count()){
ui->actionSave->setEnabled(true);
ui->actionNext->setDisabled(true);
} else {
ui->actionNext->setDisabled(false);
ui->actionSave->setEnabled(false);
}
} else {
colission->setText("Знайдено колізії.");
ui->actionNext->setDisabled(true);
ui->actionSave->setEnabled(false);
}
}
void TableWindow::itemOut(int number, bool flag){
listOutItems->setBit(number,flag);
for( int i = 0; i < listOutItems->count(); ++i ){
if(listOutItems->at(i)==true){
outItems=false;
qDebug()<<"itemOut::outItems="<<outItems<<"&& collidingItems"<<collidingItems;
checkNext();
return;
}
}
outItems=true;
checkNext();
}
void TableWindow::itemColliding(QList<QGraphicsItem *> list, int number){
//qDebug()<<"number="<<number;
if(number==0){
if(listCollidingItems.isEmpty()==false){
if(listCollidingItems.contains(list.at(0))==true){
listCollidingItems.removeAt(listCollidingItems.indexOf(list.at(0)));
if(listCollidingItems.size()>1){
for( int i = 0; i < listCollidingItems.count(); ++i ){
QList<QGraphicsItem *> l = listCollidingItems.at(i)->collidingItems();
if(l.size()-2 <= 0){
VItem * bitem = qgraphicsitem_cast<VItem *> ( listCollidingItems.at(i) );
if (bitem == 0){
qDebug()<<"Не можу привести тип об'єкту";
} else {
bitem->setPen(QPen(Qt::black, toPixel(widthMainLine)));
}
listCollidingItems.removeAt(i);
}
}
} else if(listCollidingItems.size()==1){
VItem * bitem = qgraphicsitem_cast<VItem *> ( listCollidingItems.at(0) );
if (bitem == 0){
qDebug()<<"Не можу привести тип об'єкту";
} else {
bitem->setPen(QPen(Qt::black, toPixel(widthMainLine)));
}
listCollidingItems.clear();
collidingItems = true;
}
} else {
collidingItems = true;
}
} else {
collidingItems = true;
}
} else if(number==1){
if(list.contains(paper)==true){
list.removeAt(list.indexOf(paper));
}
if(list.contains(shadowPaper)==true){
list.removeAt(list.indexOf(shadowPaper));
}
for( int i = 0; i < list.count(); ++i ){
if(listCollidingItems.contains(list.at(i))==false){
listCollidingItems.append(list.at(i));
}
}
collidingItems = false;
}
qDebug()<<"itemColliding::outItems="<<outItems<<"&& collidingItems"<<collidingItems;
checkNext();
}
void TableWindow::GetNextDetail(){
AddDetail();
}
void TableWindow::AddLength(){
QRectF rect = currentScene->sceneRect();
rect.setHeight(rect.height()+toPixel(279));
currentScene->setSceneRect(rect);
rect = shadowPaper->rect();
rect.setHeight(rect.height()+toPixel(279));
shadowPaper->setRect(rect);
rect = paper->rect();
rect.setHeight(rect.height()+toPixel(279));
paper->setRect(rect);
ui->actionRemove->setEnabled(true);
emit LengthChanged();
}
void TableWindow::RemoveLength(){
if(sceneRect.height()<=currentScene->sceneRect().height()-100){
QRectF rect = currentScene->sceneRect();
rect.setHeight(rect.height()-toPixel(279));
currentScene->setSceneRect(rect);
rect = shadowPaper->rect();
rect.setHeight(rect.height()-toPixel(279));
shadowPaper->setRect(rect);
rect = paper->rect();
rect.setHeight(rect.height()-toPixel(279));
paper->setRect(rect);
if(sceneRect.height()==currentScene->sceneRect().height()){
ui->actionRemove->setDisabled(true);
}
emit LengthChanged();
} else {
ui->actionRemove->setDisabled(true);
}
}
void TableWindow::keyPressEvent ( QKeyEvent * event ){
if( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return ){
if(ui->actionNext->isEnabled() == true ){
AddDetail();
qDebug()<<"Додали деталь.";
}
}
QMainWindow::keyPressEvent ( event );
}
void TableWindow::SvgFile(const QString &name) const{
QSvgGenerator generator;
generator.setFileName(name);
generator.setSize(paper->rect().size().toSize());
//generator.setViewBox(QRect(0, 0, 200, 200));
generator.setTitle(tr("SVG Generator Example Drawing"));
generator.setDescription(tr("An SVG drawing created by the SVG Generator "
"Example provided with Qt."));
QPainter painter;
painter.begin(&generator);
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, widthMainLine, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
currentScene->render(&painter);
painter.end();
}
void TableWindow::PngFile(const QString &name) const{
QRectF r = paper->rect();
qreal x=0, y=0, w=0, h=0;
r.getRect(&x,&y,&w,&h);// Re-shrink the scene to it's bounding contents
QImage image(QSize(w, h), QImage::Format_ARGB32); // Create the image with the exact size of the shrunk scene
image.fill(Qt::transparent); // Start all pixels transparent
QPainter painter(&image);
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, toPixel(widthMainLine), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
currentScene->render(&painter);
image.save(name);
}
void TableWindow::PsFile(const QString &name) const{
QPrinter printer(QPrinter::HighResolution);
//printer.setOutputFormat(QPrinter::PostScriptFormat);
printer.setOutputFileName(name);
QRectF r = paper->rect();
qreal x=0, y=0, w=0, h=0;
r.getRect(&x,&y,&w,&h);
printer.setResolution(PrintDPI);
qDebug()<<printer.resolution();
printer.setPaperSize ( QSizeF(w/printer.resolution()*25.4, h/printer.resolution()*25.4), QPrinter::Millimeter );
QPainter painter;
if (! painter.begin( &printer )) { // failed to open file
qCritical("Не можу відкрити файл %s",qPrintable(name));
return;
}
painter.setFont( QFont( "Arial", 8, QFont::Normal ) );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, widthMainLine, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush ( QBrush ( Qt::NoBrush ) );
currentScene->render(&painter);
painter.end();
}

170
tablewindow.h Normal file
View File

@ -0,0 +1,170 @@
#ifndef TABLEWINDOW_H
#define TABLEWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include "widgets/vitem.h"
namespace Ui {
class TableWindow;
}
/**
* @brief TableWindow клас вікна створення розкладки.
*/
class TableWindow : public QMainWindow{
Q_OBJECT
public:
/**
* @brief numberDetal Виводиться кількість деталей що ще залишилися.
*/
QLabel* numberDetal;
/**
* @brief colission Виводиться чи є колізії.
*/
QLabel* colission;
/**
* @brief TableWindow Конструктор класу вікна створення розкладки.
* @param parent Батько об'єкту. За замовчуванням = 0.
*/
explicit TableWindow(QWidget *parent = 0);
/**
* @brief ~TableWindow Деструктор класу вікна.
*/
~TableWindow();
public slots:
/**
* @brief ModelChosen Слот, що виконується при отриманні сигналу про розрахунок всіх деталей
*моделі.
* @param listDetails Список моделей деталі.
*/
void ModelChosen(QVector<VItem*> listDetails);
/**
* @brief StopTable Слот, що виконується при хованні вікна. Виконує неохідні очищення і ховає
*вікно.
*/
void StopTable();
/**
* @brief saveScene Слот виконується при натисненні кнопки зберегти.
*/
void saveScene();
/**
* @brief GetNextDetail Слот виконується при натисненні кнопки наступна деталь.
*/
void GetNextDetail();
/**
* @brief itemChect Відключає можливість виклику перевороту, якщо не вибрано жодної деталі.
* @param flag Булеве значення що регулює стан кнопки.
*/
void itemChect(bool flag);
/**
* @brief itemOut Слот, що виконується при отриманні сигналу виходу за межі листа.
* @param number Номер деталі в списку що вийшла за межі.
* @param flag Зберігає стан деталі.
*/
void itemOut(int number, bool flag);
/**
* @brief itemColliding Сигнал, що виконується при отриманні сигналу колізії об'єктів.
* @param list Список об'єктів що перетинаються.
* @param number 0 - включити до списку деталей що перетинаються, 1 - виключити зі списку.
*/
void itemColliding(QList<QGraphicsItem *> list, int number);
/**
* @brief AddLength Збільшує довжину листа на певне значення за один раз.
*/
void AddLength();
/**
* @brief RemoveLength Зменшує довжину листа на певне знечення за один раз.
*Зменшення відбувається до мінімально заданого значення.
*/
void RemoveLength();
signals:
/**
* @brief closed Сигнал посилається при хованні вікна.
*/
void closed();
/**
* @brief LengthChanged Сигнал посилається при зміні розміру листа.
*/
void LengthChanged();
protected:
/**
* @brief closeEvent Перехоплення події закриття.
* @param event Подія що отримується.
*/
void closeEvent(QCloseEvent *event);
/**
* @brief moveToCenter Переміщує вікно у центер екрану.
*/
void moveToCenter();
/**
* @brief showEvent Перехоплення події показу вікна для розміщення його поцентру.
* @param event Подія що отримується.
*/
void showEvent ( QShowEvent * event );
void keyPressEvent ( QKeyEvent * event );
private:
/**
* @brief ui Змінна для доступу до об'єктів вікна.
*/
Ui::TableWindow* ui;
/**
* @brief listDetails Список деталей на укладання.
*/
QVector<VItem*> listDetails;
/**
* @brief outItems Змінна зберігає показує чи маємо деталі що виходять за межі листа.
*/
bool outItems;
/**
* @brief collidingItems Змінна показує чи маємо деталі що перетинаються.
*/
bool collidingItems;
/**
* @brief currentScene Зберігається покажчик на сцену.
*/
QGraphicsScene* currentScene;
/**
* @brief paper Зберігається покажчик на прямокутник що імітує листа паперу.
*/
QGraphicsRectItem* paper;
/**
* @brief shadowPaper Зберігається покажчик на прямокутник що імітує тінь листа паперу.
*/
QGraphicsRectItem* shadowPaper;
/**
* @brief checkNext Метод регулює стан кнопки Next.
*/
void checkNext();
/**
* @brief listOutItems Список стану виходу за лист кожної деталі.
*/
QBitArray* listOutItems;
/**
* @brief listCollidingItems Список що зберігає деталі що перетинаються між собою.
*/
QList<QGraphicsItem*> listCollidingItems;
/**
* @brief AddPaper Додає на сцену лист паперу з тінню.
*/
void AddPaper();
/**
* @brief AddDetail Додає наступну деталь.
*/
void AddDetail();
/**
* @brief indexDetail Індекс деталі в списку, що буде викладатися наступного разу.
*/
qint32 indexDetail;
/**
* @brief sceneRect Мінімальний розмір листа паперу що буде показуватися на сцені.
*/
QRectF sceneRect;
TableWindow(const TableWindow &window);
const TableWindow &operator=(const TableWindow& window);
void SvgFile(const QString &name)const;
void PngFile(const QString &name)const;
void PsFile(const QString &name)const;
};
#endif // TABLEWINDOW_H

186
tablewindow.ui Normal file
View File

@ -0,0 +1,186 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>TableWindow</class>
<widget class="QMainWindow" name="TableWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1000</width>
<height>730</height>
</rect>
</property>
<property name="windowTitle">
<string>Створення розкладки</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetMinAndMaxSize</enum>
</property>
<property name="margin">
<number>9</number>
</property>
</layout>
</widget>
<widget class="QToolBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<property name="iconSize">
<size>
<width>16</width>
<height>16</height>
</size>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonIconOnly</enum>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionSave"/>
<addaction name="actionNext"/>
<addaction name="actionTurn"/>
<addaction name="actionAdd"/>
<addaction name="actionRemove"/>
<addaction name="actionMirror"/>
<addaction name="actionZoomIn"/>
<addaction name="actionZoomOut"/>
<addaction name="actionStop"/>
</widget>
<widget class="QStatusBar" name="statusBar"/>
<action name="actionSave">
<property name="enabled">
<bool>false</bool>
</property>
<property name="icon">
<iconset theme="document-save-as">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Зберегти</string>
</property>
<property name="toolTip">
<string>Зберегти розкладку</string>
</property>
</action>
<action name="actionNext">
<property name="icon">
<iconset theme="go-next">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Наступна</string>
</property>
<property name="toolTip">
<string>Наступна деталь</string>
</property>
</action>
<action name="actionTurn">
<property name="enabled">
<bool>false</bool>
</property>
<property name="icon">
<iconset theme="object-rotate-left">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Перевернути</string>
</property>
<property name="toolTip">
<string>Перевернути деталь на 180 градусів</string>
</property>
</action>
<action name="actionStop">
<property name="icon">
<iconset theme="process-stop">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Stop</string>
</property>
<property name="toolTip">
<string>Припинити укладання</string>
</property>
</action>
<action name="actionAdd">
<property name="icon">
<iconset theme="list-add">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Збільшити лист</string>
</property>
<property name="toolTip">
<string>Збільшити довжину листа</string>
</property>
</action>
<action name="actionRemove">
<property name="enabled">
<bool>false</bool>
</property>
<property name="icon">
<iconset theme="list-remove">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Зменшити лист</string>
</property>
<property name="toolTip">
<string>Зменшити довжину листа</string>
</property>
</action>
<action name="actionMirror">
<property name="enabled">
<bool>false</bool>
</property>
<property name="icon">
<iconset resource="icon.qrc">
<normaloff>:/icon/16x16/mirror.png</normaloff>:/icon/16x16/mirror.png</iconset>
</property>
<property name="text">
<string>Відзеркалити</string>
</property>
<property name="toolTip">
<string>Дзеркальне зображення деталі</string>
</property>
</action>
<action name="actionZoomIn">
<property name="icon">
<iconset theme="zoom-in">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Збільшити</string>
</property>
<property name="toolTip">
<string>Збільшити</string>
</property>
</action>
<action name="actionZoomOut">
<property name="icon">
<iconset theme="zoom-out">
<normaloff/>
</iconset>
</property>
<property name="text">
<string>Зменшити</string>
</property>
</action>
</widget>
<resources>
<include location="icon.qrc"/>
</resources>
<connections/>
</ui>

View File

@ -103,10 +103,6 @@ const VContainer *VAbstractTool::getData()const{
return &data;
}
void VAbstractTool::setData(const VContainer &value){
data = value;
}
void VAbstractTool::setDialog(){
}

View File

@ -56,7 +56,6 @@ protected:
void AddAttribute(QDomElement &domElement, const QString &name, const QString &value);
void AddToDraw(const QDomElement &domElement);
const VContainer *getData() const;
void setData(const VContainer &value);
template <typename Dialog, typename Tool>
void ContextMenu(QSharedPointer<Dialog> &dialog, Tool *tool, QGraphicsSceneContextMenuEvent *event,
bool showRemove = true){

View File

@ -20,5 +20,6 @@ VContainer VDataTool::getData() const{
}
void VDataTool::setData(const VContainer *value){
data.Clear();
data = *value;
}

View File

@ -51,8 +51,8 @@ void VModelingArc::ShowTool(qint64 id, Qt::GlobalColor color, bool enable){
}
}
void VModelingArc::FullUpdateFromGui(int result)
{
void VModelingArc::FullUpdateFromGui(int result){
Q_UNUSED(result);
}
void VModelingArc::AddToFile(){

View File

@ -32,8 +32,8 @@ void VModelingPoint::FullUpdateFromFile(){
RefreshGeometry();
}
void VModelingPoint::FullUpdateFromGui(int result)
{
void VModelingPoint::FullUpdateFromGui(int result){
Q_UNUSED(result);
}
void VModelingPoint::AddToFile(){

View File

@ -52,8 +52,8 @@ void VModelingSpline::ShowTool(qint64 id, Qt::GlobalColor color, bool enable){
}
}
void VModelingSpline::FullUpdateFromGui(int result)
{
void VModelingSpline::FullUpdateFromGui(int result){
Q_UNUSED(result);
}
void VModelingSpline::AddToFile(){

View File

@ -53,8 +53,8 @@ void VModelingSplinePath::ShowTool(qint64 id, Qt::GlobalColor color, bool enable
}
}
void VModelingSplinePath::FullUpdateFromGui(int result)
{
void VModelingSplinePath::FullUpdateFromGui(int result){
Q_UNUSED(result);
}
void VModelingSplinePath::AddToFile(){

View File

@ -118,7 +118,6 @@ void VToolAlongLine::Create(const qint64 _id, const QString &pointName, const QS
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -80,7 +80,6 @@ void VToolArc::Create(const qint64 _id, const qint64 &center, const QString &rad
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Arc);
}
}

View File

@ -80,7 +80,6 @@ void VToolBisector::Create(const qint64 _id, const QString &formula, const qint6
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -142,14 +142,12 @@ void VToolDetail::Create(const qint64 _id, VDetail &newDetail, VDetail &oldDetai
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
}
for(qint32 i = 0; i< newDetail.CountNode(); ++i){
VDataTool *tool = tools->value(newDetail[i].getId());
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
}
}
}
@ -168,8 +166,8 @@ void VToolDetail::FullUpdateFromFile(){
RefreshGeometry();
}
void VToolDetail::FullUpdateFromGui(int result)
{
void VToolDetail::FullUpdateFromGui(int result){
Q_UNUSED(result);
}
void VToolDetail::AddToFile(){
@ -213,16 +211,18 @@ void VToolDetail::AddNode(QDomElement &domElement, VNodeDetail &node){
AddAttribute(nod, "id", node.getId());
switch(node.getTypeTool()){
case(Scene::Point):
case(Scene::Line):
break;
case(Scene::Point):
AddAttribute(nod, "type", "Point");
break;
case(Scene::Arc):
case(Scene::Arc):
AddAttribute(nod, "type", "Arc");
break;
case(Scene::Spline):
case(Scene::Spline):
AddAttribute(nod, "type", "Spline");
break;
case(Scene::SplinePath):
case(Scene::SplinePath):
AddAttribute(nod, "type", "SplinePath");
break;
}
@ -231,38 +231,6 @@ void VToolDetail::AddNode(QDomElement &domElement, VNodeDetail &node){
}
void VToolDetail::RefreshGeometry(){
QVector<QPointF> points;
VDetail detail = VAbstractTool::data.GetDetail(id);
for(qint32 i = 0; i< detail.CountNode(); ++i){
switch(detail[i].getTypeTool()){
case(Scene::Point):{
VPointF point = VAbstractTool::data.GetModelingPoint(detail[i].getId());
points.append(point.toQPointF());
}
break;
case(Scene::Arc):{
VArc arc = VAbstractTool::data.GetModelingArc(detail[i].getId());
points << arc.GetPoints();
}
break;
case(Scene::Spline):{
VSpline spline = VAbstractTool::data.GetModelingSpline(detail[i].getId());
points << spline.GetPoints();
}
break;
case(Scene::SplinePath):{
VSplinePath splinePath = VAbstractTool::data.GetModelingSplinePath(detail[i].getId());
points << splinePath.GetPathPoints();
}
break;
}
}
QPainterPath path;
path.moveTo(points[0]);
for (qint32 i = 1; i < points.count(); ++i){
path.lineTo(points[i]);
}
path.lineTo(points[0]);
QPainterPath path = VAbstractTool::data.ContourPath(id);
this->setPath(path);
//this->setPos(detail.getMx(), detail.getMy());
}

View File

@ -63,7 +63,6 @@ void VToolEndLine::Create(const qint64 _id, const QString &pointName, const QStr
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -50,7 +50,6 @@ void VToolLine::Create(const qint64 &id, const qint64 &firstPoint, const qint64
VDataTool *tool = tools->value(id);
Q_CHECK_PTR(tool);
tool->VDataTool::setData(data);
tools->insert(id, tool);
}
VAbstractTool::AddRecord(id, Tools::LineTool, doc);
if(mode == Draw::Modeling){

View File

@ -64,7 +64,6 @@ void VToolLineIntersect::Create(const qint64 _id, const qint64 &p1Line1Id, const
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -68,7 +68,6 @@ void VToolNormal::Create(const qint64 _id, const QString &formula, const qint64
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -83,7 +83,6 @@ void VToolPointOfContact::Create(const qint64 _id, const QString &radius, const
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -92,7 +92,6 @@ void VToolShoulderPoint::Create(const qint64 _id, const QString &formula, const
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Point);
}
}

View File

@ -87,7 +87,6 @@ void VToolSpline::Create(const qint64 _id, const qint64 &p1, const qint64 &p4, c
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::Spline);
}
}

View File

@ -65,7 +65,6 @@ void VToolSplinePath::Create(const qint64 _id, const VSplinePath &path, VMainGra
VDataTool *tool = tools->value(id);
if(tool != 0){
tool->VDataTool::setData(data);
tools->insert(id, tool);
data->IncrementReferens(id, Scene::SplinePath);
}
}

62
widgets/vitem.cpp Normal file
View File

@ -0,0 +1,62 @@
#include "vitem.h"
#include <QGraphicsScene>
#include <QDebug>
#include "../options.h"
VItem::VItem():numInOutList(0){
}
VItem::VItem ( int numInList, QGraphicsItem * parent ):QGraphicsPathItem ( parent ),
numInOutList(numInList){
}
VItem::VItem (const QPainterPath & path, int numInList, QGraphicsItem * parent ):
QGraphicsPathItem ( path, parent ), numInOutList(numInList){
}
void VItem::checkItemChange(){
QRectF rect = parentItem()->sceneBoundingRect();
QRectF myrect = sceneBoundingRect();
if( rect.contains( myrect )==true ){
qDebug()<<"Не виходить за рамки листа";
setPen(QPen(Qt::black, widthMainLine));
emit itemOut( numInOutList, false );
} else {
qDebug()<<"Виходить за рамки листа";
setPen(QPen(Qt::red, widthMainLine));
emit itemOut( numInOutList, true );
}
QList<QGraphicsItem *> list = QGraphicsItem::collidingItems ();
if( list.size() - 2 > 0 ){
list.append( this );
setPen(QPen(Qt::red, widthMainLine));
qDebug()<<"Деталь перетинається з іншими деталями "<<numInOutList;
emit itemColliding( list, 1 );//Деталь перетинається з іншими деталями.
} else {
QList<QGraphicsItem *> itemList;
itemList.append( this );
qDebug()<<"Деталь більше не перетинається з іншими деталями "<<numInOutList;
emit itemColliding( itemList, 0 );//Деталь більше не перетинається з іншими деталями.
}
//qDebug()<<"list="<<list.size();
}
QVariant VItem::itemChange( GraphicsItemChange change, const QVariant &value ){
if ( change == QGraphicsItem::ItemPositionHasChanged && scene() ) {
checkItemChange();
return QGraphicsPathItem::itemChange( change, value );
}
if ( change == QGraphicsItem::ItemParentHasChanged && scene() ) {
checkItemChange();
return QGraphicsPathItem::itemChange( change, value );
}
return QGraphicsPathItem::itemChange( change, value );
}
void VItem::LengthChanged(){
checkItemChange();
}
void VItem::SetIndexInList( qint32 index ){
numInOutList = index;
}

83
widgets/vitem.h Normal file
View File

@ -0,0 +1,83 @@
#ifndef VITEM_H
#define VITEM_H
#include <QGraphicsPathItem>
#include <QObject>
/**
* @brief VItem клас, що реалізує деталь на сцені.
*/
class VItem : public QObject, public QGraphicsPathItem{
Q_OBJECT
public:
/**
* @brief VItem конструктор за замовчуванням
*Конструктор генерує пусту деталь з номером в списку, що дорівнює 0.
*/
VItem ();
/**
* @brief VItem конструктор
* @param numInList номер в списку деталей, що передається у вікно де
*укладаються деталі.
* @param parent батьківський об'єкт на сцені для даного. За замовчуванням немає.
*/
VItem (int numInList, QGraphicsItem * parent = 0);
/**
* @brief VItem конструктор
* @param path зображення що буде показуватися на сцені - обєкт класу QPainterPath.
* @param numInList номер в списку деталей, що передається у вікно де
*укладаються деталі.
* @param parent батьківський об'єкт на сцені для даного. За замовчуванням немає.
*/
VItem ( const QPainterPath & path, int numInList, QGraphicsItem * parent = 0 );
/**
* @brief Rotate повертає об'єкт на кут в градусах
* @param angle кут в градусах на який повертається деталь.
*/
void Rotate ( qreal angle );
public slots:
/**
* @brief LengthChanged слот який обробляє сигнал зміни довжини листа.
*/
void LengthChanged();
/**
* @brief SetIndexInList встановлює номер деталі в списку деталей.
* @param index номер в списку.
*/
void SetIndexInList( qint32 index );
protected:
/**
* @brief itemChange модифікація стандартного методу itemChange. Виконується перехоплення зміни
*положення і зміни батька.
* @param change
* @param value
* @return
*/
QVariant itemChange ( GraphicsItemChange change, const QVariant &value );
/**
* @brief checkItemChange перевіряє вихід деталі за рамки листа і факт колізії. Посилає відповідні
*сигнали.
*/
void checkItemChange ();
private:
/**
* @brief numInOutList для зберігання інформації про колізії від кожної деталі необхідно знати її
*номер.
*/
qint32 numInOutList;
signals:
/**
* @brief itemOut сигнал виходу за межі листа. Посилається у будь-якому випадку.
* @param numInOutList номер деталі яка вийшла за межі листа або тепер знаходиться в межах листа.
* @param flag був вихід чи ні.
*/
void itemOut ( int numInOutList, bool flag );
/**
* @brief itemColliding сигнал колізії деталі з іншими. Посилається як для додавання деталі до
*списку тих що перетинаються, так і для виключення його з такого.
* @param list список усіх деталей які приймають участь в колізії включаючи самого себе.
* @param number 1 - перетин є, 0 - перетину немає.
*/
void itemColliding ( QList<QGraphicsItem *> list, int number );
};
#endif // VITEM_H

View File

@ -0,0 +1,161 @@
#include "vtablegraphicsview.h"
#include <QDebug>
#include <QGraphicsItem>
#include <QGuiApplication>
#include <QKeyEvent>
#include <QScrollBar>
VTableGraphicsView::VTableGraphicsView(QGraphicsScene* pScene, QWidget *parent) :
QGraphicsView(pScene, parent){
QGraphicsView::setResizeAnchor(QGraphicsView::AnchorUnderMouse);
connect(pScene, &QGraphicsScene::selectionChanged, this, &VTableGraphicsView::selectionChanged);
}
void VTableGraphicsView::selectionChanged(){
QList<QGraphicsItem *> listSelectedItems = scene()->selectedItems();
if( listSelectedItems.isEmpty() == true ){
qDebug() << "деталь не знайдено";
emit itemChect(true);
} else {
qDebug() << "деталь знайдено";
emit itemChect(false);
}
}
void VTableGraphicsView::rotateItems(){
rotateIt();
}
void VTableGraphicsView::MirrorItem(){
QList<QGraphicsItem *> list = scene()->selectedItems();
if(list.size()>0){
for( qint32 i = 0; i < list.count(); ++i ){
QRectF itemRectOld = list.at(i)->sceneBoundingRect();
//Get the current transform
QTransform transform(list.at(i)->transform());
qreal m11 = transform.m11(); // Horizontal scaling
qreal m12 = transform.m12(); // Vertical shearing
qreal m13 = transform.m13(); // Horizontal Projection
qreal m21 = transform.m21(); // Horizontal shearing
qreal m22 = transform.m22(); // vertical scaling
qreal m23 = transform.m23(); // Vertical Projection
qreal m31 = transform.m31(); // Horizontal Position (DX)
qreal m32 = transform.m32(); // Vertical Position (DY)
qreal m33 = transform.m33(); // Addtional Projection Factor
// Horizontal flip
m11 = -m11;
// Write back to the matrix
transform.setMatrix(m11, m12, m13, m21, m22, m23, m31, m32, m33);
// Set the items transformation
list.at(i)->setTransform(transform);
QRectF itemRectNew = list.at(i)->sceneBoundingRect();
qreal dx, dy;
dx = itemRectOld.center().x()-itemRectNew.center().x();
dy = itemRectOld.center().y()-itemRectNew.center().y();
list.at(i)->moveBy(dx, dy);
}
}
}
void VTableGraphicsView::ZoomIn(){
scale(1.1,1.1);
}
void VTableGraphicsView::ZoomOut(){
scale(1/1.1,1/1.1);
}
void VTableGraphicsView::wheelEvent(QWheelEvent *event){
if (QGuiApplication::keyboardModifiers() == Qt::ControlModifier){
// Если нажата клавиша CTRL этот код выполнится
if ((event->delta())>0){
ZoomIn();
} else if ((event->delta())<0){
ZoomOut();
}
} else {
verticalScrollBar()->setValue(verticalScrollBar()->value()-event->delta());
}
}
void VTableGraphicsView::mousePressEvent(QMouseEvent *mousePress){
if(mousePress->button() & Qt::LeftButton){
switch(QGuiApplication::keyboardModifiers()){
case Qt::ControlModifier:
QGraphicsView::setDragMode(QGraphicsView::ScrollHandDrag);
QGraphicsView::mousePressEvent(mousePress);
break;
default:
QGraphicsView::mousePressEvent(mousePress);
break;
}
}
}
void VTableGraphicsView::mouseReleaseEvent(QMouseEvent *event){
QGraphicsView::mouseReleaseEvent ( event );
QGraphicsView::setDragMode( QGraphicsView::RubberBandDrag );
}
void VTableGraphicsView::keyPressEvent(QKeyEvent *event){
switch(event->key()){
case Qt::Key_Space:
rotateIt();
break;
case Qt::Key_Left:
MoveItem(VTableGraphicsView::Left);
break;
case Qt::Key_Right:
MoveItem(VTableGraphicsView::Right);
break;
case Qt::Key_Up:
MoveItem(VTableGraphicsView::Up);
break;
case Qt::Key_Down:
MoveItem(VTableGraphicsView::Down);
break;
}
QGraphicsView::keyPressEvent ( event );
}
void VTableGraphicsView::rotateIt(){
QList<QGraphicsItem *> list = scene()->selectedItems();
if(list.size()>0){
for( qint32 i = 0; i < list.count(); ++i ){
list.at(i)->setTransformOriginPoint(list.at(i)->boundingRect().center());
list.at(i)->setRotation(list.at(i)->rotation() + 180);
}
}
}
void VTableGraphicsView::MoveItem(VTableGraphicsView::typeMove_e move){
qreal dx = 0, dy = 0;
switch(move){
case VTableGraphicsView::Left:
dx = -3;
dy = 0;
break;
case VTableGraphicsView::Right:
dx = 3;
dy = 0;
break;
case VTableGraphicsView::Up:
dx = 0;
dy = -3;
break;
case VTableGraphicsView::Down:
dx = 0;
dy = 3;
break;
}
QList<QGraphicsItem *> listSelectedItems = scene()->selectedItems();
if(listSelectedItems.size()>0){
for( qint32 i = 0; i < listSelectedItems.count(); ++i ){
listSelectedItems.at(i)->moveBy(dx, dy);
}
}
}

View File

@ -0,0 +1,73 @@
#ifndef VTABLEGRAPHICSVIEW_H
#define VTABLEGRAPHICSVIEW_H
#include <QGraphicsView>
class VTableGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
enum typeMove_e { Left, Right, Up, Down };
explicit VTableGraphicsView(QGraphicsScene* pScene, QWidget *parent = 0);
signals:
/**
* @brief itemChect Сигнал, що посилається коли змінюється стан вибору деталі.
* @param flag Зберігає стан вибору деталі: false - знайдено, true - не знайдено.
*/
void itemChect( bool flag );
public slots:
/**
* @brief selectionChanged Слот виконується при зміні стану вибору деталей.
*/
void selectionChanged();
/**
* @brief rotateItems слот, який виконується при натисненні кнопки повороту деталі.
*/
void rotateItems();
/**
* @brief MirrorItem дзеркалить об'єкт відносно вертикальної вісі семетрії об'єкта.
*/
void MirrorItem();
/**
* @brief ZoomIn збільшує масштаб листа.
*/
void ZoomIn();
/**
* @brief ZoomOut зменшує масштаб листа.
*/
void ZoomOut();
protected:
/**
* @brief wheelEvent обробник повороту колеса мишки.
* @param event передається подія.
*/
void wheelEvent ( QWheelEvent * event );
/**
* @brief mousePressEvent обробник натиснення кнопки миші.
* @param mousePress передається подія.
*/
void mousePressEvent(QMouseEvent *mousePress);
/**
* @brief mouseReleaseEvent обробник відпускання кнопки миші.
* @param event передається подія
*/
void mouseReleaseEvent ( QMouseEvent * event );
/**
* @brief keyPressEvent обробник натиснення клавіші.
* @param event передається подія.
*/
void keyPressEvent ( QKeyEvent * event );
/**
* @brief rotateIt виконує поворот вибраних деталей на 180 градусів.
*/
void rotateIt();
/**
* @brief MoveItem переміщує виділені об'єкти сцени.
* @param move напрямок переміщення.
*/
void MoveItem( VTableGraphicsView::typeMove_e move );
};
#endif // VTABLEGRAPHICSVIEW_H

View File

@ -20,22 +20,24 @@
VDomDocument::VDomDocument(VContainer *data, QComboBox *comboBoxDraws) : QDomDocument(),
VDomDocument::VDomDocument(VContainer *data, QComboBox *comboBoxDraws, Draw::Mode *mode) : QDomDocument(),
map(QMap<QString, QDomElement>()), nameActivDraw(QString()), data(data),
tools(QMap<qint64, VDataTool*>()), history(QVector<VToolRecord>()), cursor(0),
comboBoxDraws(comboBoxDraws){
comboBoxDraws(comboBoxDraws), mode(mode){
}
VDomDocument::VDomDocument(const QString& name, VContainer *data, QComboBox *comboBoxDraws) :
VDomDocument::VDomDocument(const QString& name, VContainer *data, QComboBox *comboBoxDraws,
Draw::Mode *mode) :
QDomDocument(name), map(QMap<QString, QDomElement>()), nameActivDraw(QString()), data(data),
tools(QMap<qint64, VDataTool*>()), history(QVector<VToolRecord>()), cursor(0),
comboBoxDraws(comboBoxDraws){
comboBoxDraws(comboBoxDraws), mode(mode){
}
VDomDocument::VDomDocument(const QDomDocumentType& doctype, VContainer *data, QComboBox *comboBoxDraws) :
VDomDocument::VDomDocument(const QDomDocumentType& doctype, VContainer *data, QComboBox *comboBoxDraws,
Draw::Mode *mode) :
QDomDocument(doctype), map(QMap<QString, QDomElement>()), nameActivDraw(QString()), data(data),
tools(QMap<qint64, VDataTool*>()), history(QVector<VToolRecord>()), cursor(0),
comboBoxDraws(comboBoxDraws){
comboBoxDraws(comboBoxDraws), mode(mode){
}
VDomDocument::~VDomDocument(){
@ -748,29 +750,31 @@ void VDomDocument::setCursor(const qint64 &value){
}
void VDomDocument::setCurrentData(){
QString nameDraw = comboBoxDraws->itemText(comboBoxDraws->currentIndex());
if(nameActivDraw != nameDraw){
nameActivDraw = nameDraw;
qint64 id = 0;
if(history.size() == 0){
return;
}
for(qint32 i = 0; i < history.size(); ++i){
VToolRecord tool = history.at(i);
if(tool.getNameDraw() == nameDraw){
id = tool.getId();
}
}
if(id == 0){
VToolRecord tool = history.at(history.size()-1);
id = tool.getId();
if(id == 0){
if(*mode == Draw::Calculation){
QString nameDraw = comboBoxDraws->itemText(comboBoxDraws->currentIndex());
if(nameActivDraw != nameDraw){
nameActivDraw = nameDraw;
qint64 id = 0;
if(history.size() == 0){
return;
}
}
if(tools.size() > 0){
VDataTool *vTool = tools.value(id);
data->setData(vTool->getData());
for(qint32 i = 0; i < history.size(); ++i){
VToolRecord tool = history.at(i);
if(tool.getNameDraw() == nameDraw){
id = tool.getId();
}
}
if(id == 0){
VToolRecord tool = history.at(history.size()-1);
id = tool.getId();
if(id == 0){
return;
}
}
if(tools.size() > 0){
VDataTool *vTool = tools.value(id);
data->setData(vTool->getData());
}
}
}
}

View File

@ -30,9 +30,11 @@ class VDomDocument : public QObject, public QDomDocument
{
Q_OBJECT
public:
VDomDocument(VContainer *data,QComboBox *comboBoxDraws);
VDomDocument(const QString& name, VContainer *data,QComboBox *comboBoxDraws);
VDomDocument(const QDomDocumentType& doctype, VContainer *data, QComboBox *comboBoxDraws);
VDomDocument(VContainer *data,QComboBox *comboBoxDraws, Draw::Mode *mode);
VDomDocument(const QString& name, VContainer *data, QComboBox *comboBoxDraws,
Draw::Mode *mode);
VDomDocument(const QDomDocumentType& doctype, VContainer *data, QComboBox *comboBoxDraws,
Draw::Mode *mode);
~VDomDocument();
QDomElement elementById(const QString& id);
void CreateEmptyFile();
@ -70,6 +72,7 @@ private:
QVector<VToolRecord> history;
qint64 cursor;
QComboBox *comboBoxDraws;
Draw::Mode *mode;
VDomDocument(const VDomDocument & doc);
const VDomDocument &operator=(const VDomDocument& doc);
bool find(QDomElement node, const QString& id);