I created a few QLabel in my MainWindow using Qt Creator and opencv, but I have this error :
error: 'ui' was not declared in this scope
in the function filter_image(). I want to use label to show an image before and after doing some processing.
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include<QImage>
#include<QLabel>
static QImage IplImage2QImage(const IplImage *iplImage) {
int height = iplImage->height;
int width = iplImage->width;
if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3)
{
const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
QImage img(qImageBuffer, width, height, QImage::Format_RGB888);
return img.rgbSwapped();
}
else if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 1)
{
const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
QImage img(qImageBuffer, width, height, QImage::Format_Indexed8);
QVector<QRgb> colorTable;
for (int i = 0; i < 256; i++)
{
colorTable.push_back(qRgb(i, i, i));
}
img.setColorTable(colorTable);
return img;
}
else
{
std::cout << "Image cannot be converted.";
return QImage();
}
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void filter_image(IplImage* img) {
IplImage* roi = cvCreateImage(cvGetSize(img), 8, 3);
cvCvtColor( img, roi, CV_RGB2GRAY );
cvSmooth(img,roi,CV_BLUR, 5, 0, 0, 0);
cvThreshold(roi,roi,100,255,CV_THRESH_BINARY);
IplImage *img_de = cvCloneImage(roi);
QImage qt_i = IplImage2QImage(img_de);
QLabel label_2;
// display on label
ui->label_2->setPixmap(QPixmap::fromImage(qt_i));//error line
// resize the label to fit the image
ui->label_2->resize(ui->label_2->pixmap()->size());
label_2.show();
}
void MainWindow::on_actionOpen_triggered() {
IplImage *frame = cvLoadImage(
QFileDialog::getOpenFileName(this,
"Ouvrir un fichier",
"/../../Fichiers Image",
"Image (*.jpg *.bmp *.jpeg)")
.toStdString().c_str(),3);
IplImage *img_des = cvCloneImage(frame);
QImage qt_im = IplImage2QImage(img_des);
QLabel label;
// display on label
ui->label->setPixmap(QPixmap::fromImage(qt_im));
// resize the label to fit the image
ui->label->resize(ui->label->pixmap()->size());
label.show();
filter_image(frame);
}
mainwindow.h
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void changeEvent(QEvent *e);
public:
Ui::MainWindow *ui;
public slots:
void on_actionOpen_triggered();
};
ui_mainwindow.h
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QMainWindow>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QToolBar>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow{
public:
QAction *actionOpen;
QWidget *centralWidget;
QLabel *label;
QLabel *label_2;
QMenuBar *menuBar;
QMenu *menuFile;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(600, 400);
actionOpen = new QAction(MainWindow);
actionOpen->setObjectName(QString::fromUtf8("actionOpen"));
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
label = new QLabel(centralWidget);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(290, 30, 271, 301));
label_2 = new QLabel(centralWidget);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setGeometry(QRect(20, 20, 281, 331));
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 600, 21));
menuFile = new QMenu(menuBar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QString::fromUtf8("statusBar"));
MainWindow->setStatusBar(statusBar);
menuBar->addAction(menuFile->menuAction());
menuFile->addAction(actionOpen);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
actionOpen->setText(QApplication::translate("MainWindow", "Open", 0, QApplication::UnicodeUTF8));
label->setText(QString());
label_2->setText(QString());
menuFile->setTitle(QApplication::translate("MainWindow", "File", 0, QApplication::UnicodeUTF8));
} // retranslateUi};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
The method filter_image, which is where the error is occurring, is not a class method of MainWindow, so it doesn't have access to MainWindow's members (including ui).
You can do a couple of things: if it makes sense, make it part of the MainWindow class. Alternatively, you can pass the ui as a parameter:
void filter_image(Ui::MainWindow* ui, /*other params*/){...}
Also, you are making a local variable label_2 rather than taking the one from the gui.
Related
I subclassed a QPushButton so that I was able to re-implement the paintEvent(QPaintEvent *paint) method also advised by the official documentation.
Below is the sequence of operations:
a) After I launch the application the button is below:
b) This is after I hover on it:
c) then I click the button:
d) and finally I release the mouse
e) go away from the button
However the problem is that the QPainterPath with which I designed the green box it should be red after I release the button. And, of course, it should become green again after I click again the button.
Below the code:
custombutton.h
class CustomButton : public QPushButton
{
Q_OBJECT
public:
CustomButton(QWidget *parent = nullptr);
~CustomButton();
QString FirstName = "MACHINE";
QString LastName = "CONTROL";
protected:
void paintEvent(QPaintEvent *);
};
custombutton.cpp
CustomButton::CustomButton(QWidget *parent) : QPushButton(parent)
{
setGeometry(150, 150, 110, 110);
setAttribute(Qt::WA_TranslucentBackground);
setStyleSheet(
"QPushButton{background-color: lightGray;border: 1px solid black; border-radius: 5px;}"
"QPushButton:hover{background-color: gray;}"
"QPushButton:pressed{background-color: lightGray;}");
}
CustomButton::~CustomButton()
{
}
void CustomButton::paintEvent(QPaintEvent *paint)
{
QPushButton::paintEvent(paint);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(QRectF(15, 15, 80, 5), 2, 2);
QPen pen(Qt::black, 0.3);
p.setPen(pen);
p.fillPath(path, Qt::darkGreen);
p.drawPath(path);
p.save();
p.drawText(QPoint(20, 60), FirstName);
p.drawText(QPoint(20, 80), LastName);
p.setFont(QFont("Arial", 10));
p.restore();
}
mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void onClickedButton();
private:
Ui::MainWindow *ui;
CustomButton *newBtn;
};
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
newBtn = new CustomButton(this);
newBtn->show();
connect(newBtn, &QPushButton::clicked, this, &MainWindow::onClickedButton);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onClickedButton()
{
QPushButton* target = qobject_cast<QPushButton*>(sender());
if (target != nullptr)
{
QPainter p;
p.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(QRectF(15, 15, 80, 5), 2, 2);
QPen pen(Qt::black, 0.3);
p.setPen(pen);
p.fillPath(path, Qt::darkRed);
p.drawPath(path);
p.save();
p.restore();
}
}
As you see in the MainWindow I created a function onClickedButton() which I thought would have triggered the QPainterPath into red after clicked. And in order to do that I casted it into an object (qobject_cast). But unfortunately it didn't work as expexted.
The solution is to create a flag that indicates the color and call update() for repainting:
#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H
#include <QPushButton>
class CustomButton : public QPushButton
{
Q_OBJECT
public:
CustomButton(QWidget *parent = nullptr);
~CustomButton();
QString FirstName = "MACHINE";
QString LastName = "CONTROL";
private Q_SLOTS:
void handleClicked();
protected:
void paintEvent(QPaintEvent *);
private:
bool state;
};
#endif // CUSTOMBUTTON_H
#include "custombutton.h"
#include <QPainter>
#include <QPainterPath>
CustomButton::CustomButton(QWidget *parent) : QPushButton(parent), state(true)
{
setGeometry(150, 150, 110, 110);
setAttribute(Qt::WA_TranslucentBackground);
setStyleSheet(
"QPushButton{background-color: lightGray;border: 1px solid black; border-radius: 5px;}"
"QPushButton:hover{background-color: gray;}"
"QPushButton:pressed{background-color: lightGray;}");
connect(this, &QPushButton::clicked, this, &CustomButton::handleClicked);
}
CustomButton::~CustomButton()
{
}
void CustomButton::handleClicked()
{
state = !state;
update();
}
void CustomButton::paintEvent(QPaintEvent *paint)
{
QPushButton::paintEvent(paint);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(QRectF(15, 15, 80, 5), 2, 2);
QPen pen(Qt::black, 0.3);
p.setPen(pen);
p.fillPath(path, state ? Qt::darkGreen: Qt::darkRed);
p.drawPath(path);
p.drawText(QPoint(20, 60), FirstName);
p.drawText(QPoint(20, 80), LastName);
p.setFont(QFont("Arial", 10));
}
I'm creating a very simple disk space analyzer that shows ocupied size of every file in specific foder and its subfolders. I'm using QStack to store paths and QTableWidget for showing next information (File Name, File Path, File Size and Last Modified Date). First of all I use QDirIterator to fill QStack, then in different thread I get necessary information about file by QFileInfo and add row in QTableWidget with this information. Populating QStack is quick but filling QTableWidget is very slow. The question is how can I boost speed of filling QTableWidget.
dialog.h
#include <QDialog>
#include <QStack>
#include "mythread.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
MyThread *mThread;
QStack<QString> *fileStack;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
public slots:
void onFileAdded(QString file);
private:
Ui::Dialog *ui;
};
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include "mythread.h"
#include <QFileDialog>
#include <QDirIterator>
#include <QMessageBox>
#include <QFileInfo>
#include <QDateTime>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
ui->tableWidget->setColumnCount(4);
ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "File name" << "File Path" << "File Size (KB)" << "Last Modified Date");
fileStack = new QStack<QString>();
ui->tableWidget->setSortingEnabled(true);
mThread = new MyThread(this);
connect(mThread, SIGNAL(fileAdded(QString)), this, SLOT(onFileAdded(QString)));
}
Dialog::~Dialog()
{
delete ui;
delete mThread;
delete fileStack;
}
void Dialog::onFileAdded(QString file) {
QFileInfo fileInfo;
fileInfo.setFile(file);
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1,
0,
new QTableWidgetItem(fileInfo.fileName()));
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1,
1,
new QTableWidgetItem(fileInfo.filePath()));
int sss = fileInfo.size() / 1024;
QTableWidgetItem *item = new QTableWidgetItem;
item->setData(Qt::EditRole, sss);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1,
2,
item);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1,
3,
new QTableWidgetItem(fileInfo.lastModified().toString()));
//ui->tableWidget->resizeColumnsToContents();
//ui->tableWidget->resizeRowsToContents();
}
void Dialog::on_pushButton_clicked()
{
QString dirname = QFileDialog::getExistingDirectory(this, tr("Select a Directory"), QDir::currentPath());
ui->lineEdit->setText(dirname);
}
void Dialog::on_pushButton_2_clicked()
{
QDirIterator it(ui->lineEdit->text(), QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
fileStack->push(it.next());
}
QMessageBox msgBox;
msgBox.setText("Completed");
msgBox.exec();
mThread->dir = fileStack;
mThread->start();
}
I have the following code which is a modification of the code given by OpenSceneGraph (https://github.com/openscenegraph/osg/blob/master/examples/osgviewerQt/osgviewerQt.cpp) for integrating OSG with Qt:
OSGViewer.h
#ifndef OSGVIEWER_H
#define OSGVIEWER_H
#include <QTimer>
#include <QApplication>
#include <QGridLayout>
#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/MultiTouchTrackballManipulator>
#include <osgDB/ReadFile>
#include <osgQt/GraphicsWindowQt>
#include <QGLWidget>
class ViewerWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
ViewerWidget(QWidget* parent = 0, osgViewer::ViewerBase::ThreadingModel threadingModel=osgViewer::CompositeViewer::SingleThreaded);
QWidget* addViewWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene );
osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false );
virtual void paintEvent( QPaintEvent* event ) { frame(); }
QTimer _timer;
};
#endif // OSGVIEWER_H
OSGViewer.cpp
#include "OSGViewer.h"
ViewerWidget::ViewerWidget(QWidget* parent, osgViewer::ViewerBase::ThreadingModel threadingModel)
{
setThreadingModel(threadingModel);
connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
_timer.start( 10 );
}
QWidget* ViewerWidget::addViewWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )
{
osgViewer::View* view = new osgViewer::View;
addView( view );
osg::Camera* camera = view->getCamera();
camera->setGraphicsContext( gw );
const osg::GraphicsContext::Traits* traits = gw->getTraits();
camera->setClearColor( osg::Vec4(0, 0, 0, 1.0) );
camera->setViewport( new osg::Viewport(0, 0, this->width(), this->height()) );
camera->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
view->setSceneData( scene );
view->addEventHandler( new osgViewer::StatsHandler );
view->setCameraManipulator( new osgGA::MultiTouchTrackballManipulator );
gw->setTouchEventsEnabled( true );
return gw->getGLWidget();
}
osgQt::GraphicsWindowQt* ViewerWidget::createGraphicsWindow( int x, int y, int w, int h, const std::string& name, bool windowDecoration )
{
osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->windowName = name;
traits->windowDecoration = windowDecoration;
traits->x = x;
traits->y = y;
traits->width = w;
traits->height = h;
traits->doubleBuffer = true;
traits->alpha = ds->getMinimumNumAlphaBits();
traits->stencil = ds->getMinimumNumStencilBits();
traits->sampleBuffers = ds->getMultiSamples();
traits->samples = ds->getNumMultiSamples();
return new osgQt::GraphicsWindowQt(traits.get());
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "OSGViewer.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
//void onCreateView();
private:
Ui::MainWindow *ui;
osg::ref_ptr<ViewerWidget> m_osgViewer_right, m_osgViewer_left;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_osgViewer_left = new ViewerWidget(this);
ui->left = m_osgViewer_left->addViewWidget(m_osgViewer_left->createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("cessnafire.osg") );
m_osgViewer_left->show();
m_osgViewer_right = new ViewerWidget;
ui->right = m_osgViewer_right->addViewWidget(m_osgViewer_right->createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("cow.osgt") );
m_osgViewer_right->show();
ui->gridLayout->addWidget( ui->left, 0, 0 );
ui->gridLayout->addWidget( ui->right, 0, 2 );
}
/* ------------------------------------------------------- */
MainWindow::~MainWindow()
{
delete ui;
}
Although I can render two objects using two different QWidgets in my MainWindow, I always have another two separate empty windows that pop up behind my MainWindow. If I close them, then I cannot render my models any more in my MainWindow. Any ideas how to solve this? I'm new to OpenSceneGraph.
I'm working on a Qt project. A point must be drawn on a mouse click on a Qpainter area. The point position is supposed to be on the same exact position of the mouse click, but for some reason the point is drawn in another position diagonal to the expected position.
The code :
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
QGraphicsView * view = new QGraphicsView(this) ;
ui->setupUi(this);
QGridLayout * gridLayout = new QGridLayout(ui->centralWidget);
gridLayout->addWidget(view);
scene = new QGraphicsScene();
scene->setSceneRect(50, 50, 350, 350);
view->setScene(scene);
}
void MainWindow::mousePressEvent(QMouseEvent * e)
{
QGraphicsView * view = new QGraphicsView(this) ;
double rad = 1;
QPointF pt = view->mapToScene(e->pos());
scene->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,QPen(), QBrush(Qt::SolidPattern));
}
Your code is not correct. You create heavy view every clicking, you should not do this. If you want that user will be able to interact with scene, then create new custom scene and do all hat you need in scene.
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
#include <QPoint>
#include <QMouseEvent>
class GraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit GraphicsScene(QObject *parent = 0);
~GraphicsScene();
signals:
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
public slots:
private:
};
#endif // GRAPHICSSCENE_H
cpp:
#include "graphicsscene.h"
#include <QDebug>
GraphicsScene::GraphicsScene(QObject *parent) :
QGraphicsScene(parent)
{
}
GraphicsScene::~GraphicsScene()
{
qDebug() << "deleted scene";
}
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == Qt::LeftButton)
{
double rad = 1;
QPointF pt = mouseEvent->scenePos();
this->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,QPen(),
QBrush(Qt::SolidPattern));
}
QGraphicsScene::mousePressEvent(mouseEvent);
}
Usage, for example:
#include "graphicsscene.h"
//...
GraphicsScene *scene = new GraphicsScene(this);
someview->setScene(scene);
I have drawn a QRubberband on QLabel. i can resize it using QSizeGrip. Now I want to move it from one point to another using QMouseevents. Is there any one who can help me out.
void CropImage::mousePressEvent(QMouseEvent *event)
{
QLabel::mousePressEvent(event);
lastPoint = event->pos();
rubberband = new QRubberBand(QRubberBand::Rectangle,this);
rubberband->setGeometry(QRect(lastPoint, QSize()));
rubberband->show();
}
void CropImage::mouseReleaseEvent(QMouseEvent *event)
{
newPoint = event->pos();
}
this is my subclass part which is used for mouse events. the code is as following:
Resizable_rubber_band::Resizable_rubber_band(QWidget *parent) : QWidget(parent)
{
//tell QSizeGrip to resize this widget instead of top-level window
setWindowFlags(Qt::SubWindow);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
QSizeGrip* grip1 = new QSizeGrip(this);
QSizeGrip* grip2 = new QSizeGrip(this);
layout->addWidget(grip1, 0, Qt::AlignLeft | Qt::AlignTop);
layout->addWidget(grip2, 0, Qt::AlignRight | Qt::AlignBottom);
rubberband = new QRubberBand(QRubberBand::Rectangle, this);
rubberband->move(0, 0);
rubberband->show();
}
void Resizable_rubber_band::resizeEvent(QResizeEvent *)
{
rubberband->resize(size());
}
void Resizable_rubber_band::mousePressEvent(QMouseEvent *event)
{
lastPoint = event->pos();
rubberband->childAt(lastPoint);
}
void Resizable_rubber_band::mouseReleaseEvent(QMouseEvent *event)
{
newpoint = event->pos();
int dragx=newpoint.x()-lastPoint.x();
int dragy=newpoint.y()-lastPoint.y();
band->move(0+dragx,0+dragy);
}
In this code, my problem is i am not getting the exact coordinates after dragging
thanks.
Ashish
Here is a quick example I made where you can move a QRubberBand using mouse events:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QRubberBand>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
private:
Ui::MainWindow *ui;
QRubberBand *rubberBand;
bool move_rubberband;
QPoint rubberband_offset;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
move_rubberband = false;
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
rubberBand->setGeometry(0,0,50,50);
rubberBand->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent *e)
{
if(rubberBand->geometry().contains(e->pos()))
{
rubberband_offset = e->pos() - rubberBand->pos();
move_rubberband = true;
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
if(move_rubberband)
{
rubberBand->move(e->pos() - rubberband_offset);
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
move_rubberband = false;
}