QT滑鼠點選響應事件
比如我們有一個widget視窗,該窗口裡有一個PixmapLabel圖片,
我們假設想在圖片的左上角響應滑鼠的點選事件,那麼我們可以這樣做!
1. 建立一個新類
//mainForm.h
#ifndef MAINFORM_H
#define MAINFORM_H
#include <qevent.h>
#include <qvariant.h>
#include <qwidget.h>
#include <qmessagebox.h>
class QVBoxLayout;
class QHBoxLayout;
class QGridLayout;
class QLabel;
class mainForm : public QWidget
{
Q_OBJECT
public:
mainForm( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 );
~mainForm();
QLabel* myPixmapLabel;
signals:
void clicked();
public slots:
virtual void mousePressEventSlot();
protected:
void mousePressEvent(QMouseEvent *);
protected slots:
virtual void languageChange();
};
#endif // MAINFORM_H
2. 實現檔案
//mainForm.cpp
#include "mainForm.h"
#include <qvariant.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
/*
* Constructs a mainForm as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
mainForm::mainForm( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "mainForm" );
//setCaption("Qt Mouse Click Event Example");
myPixmapLabel = new QLabel( this, "myPixmapLabel" );
myPixmapLabel->setGeometry( QRect( 120, 60, 300, 270 ) );
//放置一個圖片,該圖片應該在同一資料夾裡,否則要指定路徑
myPixmapLabel->setPixmap( QPixmap::fromMimeSource( "about-to-install.png" ) );
myPixmapLabel->setScaledContents( TRUE );
languageChange();
resize( QSize(600, 480).expandedTo(minimumSizeHint()) );
connect( this, SIGNAL( clicked() ), this, SLOT( mousePressEventSlot() ) ); //訊號連線
}
/*
* Destroys the object and frees any allocated resources
*/
mainForm::~mainForm()
{
// no need to delete child widgets, Qt does it all for us
}
void mainForm::mousePressEvent(QMouseEvent *e)
{
int x = e->x();
int y = e->y();
//假如在QRect( 120, 60, 200, 200 ) );這個區域裡,就發出訊號
if (x>120 && x<200 && y>60 && y<200)
emit clicked();
}
void mainForm::mousePressEventSlot()
{
//該訊號響應的曹
//給出一個提示資訊
QMessageBox::about( this, "Qt Mouse Click Event Example",
"You haved clicked the prearranged position /nand the widget will be closed."
);
close(); //關閉程式
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void mainForm::languageChange()
{
setCaption( tr( "Qt Mouse Click Event Example" ) );
}
3. main 函式
//main.cpp
#include <qapplication.h>
#include "mainForm.h"
int main( int argc, char ** argv )
{
QApplication a( argc, argv );
mainForm w;
w.show();
a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
return a.exec();
}
將三個上述檔案放在同一資料夾裡,然後新建 pro 檔案:
TEMPLATE = app
INCLUDEPATH += .
# Input
HEADERS += mainForm.h
SOURCES += main.cpp mainForm.cpp
然後:
qmake
make
直接執行,看看效果如何?