Define the main module that shows the widget
1: #include <QtGui>2: #include "CustomWidget.h"3:4: int main( int argc, char **argv )5: {6: QApplication app( argc, argv );7:8: CustomWidget theCustomWidget;9: CustomWidget.show();10:11: return app.exec();12: }
The custom widget header file define a slot allows other modules to connect in order to get mouse clicking events from the widget .
1: #include <QtGui>2: #include <QWidget>3:4: class CustomWidget : public QWidget5: {6: Q_OBJECT7: public:8: CustomWidget();9:10: protected:11: void paintEvent(QPaintEvent *event);12: void mouseReleaseEvent ( QMouseEvent * e );13: void mousePressEvent ( QMouseEvent * e );14: private:15: QPoint m_lastPoint;16: // member variable - flag of click beginning17: bool mWasMouseClicking;18:19: signals:20: void OnMouseClick(QPoint pPos);21: public slots:22:23: private:24: bool CheckIfPointInWidget (QPoint pPos);25: int DistanceBetweenpoints (QPoint pFirstPt , QPoint pSecondPt);26: };
The custom widget implementation cpp file.
1: #include "CustomWidget.h"2:3: void CustomWidget::paintEvent(QPaintEvent *event)4: {5: //create a QPainter and pass a pointer to the device.6: QPainter painter(this);7:8: painter.drawPolygon(polygon);9:10: //draw the widget for an example an ellipse11: //Enables antialiasing,12: //set QPainter to use different13: //color intensities on the edges to reduce the visual distortion that normally14: //occurs when the edges of a shape are converted into pixels15: painter.setRenderHint(QPainter::Antialiasing, true);16:17: //Set the inner and the outer colors18: painter.setPen(QPen(Qt::pink, 4, Qt::DashLine, Qt::RoundCap));19: painter.setBrush(QBrush(Qt::blue, Qt::Dense5Pattern));20:21: painter.drawEllipse(200, 50, 250, 100);22: }23:24: void CustomWidget::mousePressEvent ( QMouseEvent * e )25: {26: if ( CheckIfPointInWidget (e->pos()) == false )27: {28: return ;29: }30:31: m_lastPoint = e->pos();32: // set the flag meaning "click begin"33: mWasMouseClicking = true;34: }35: void CustomWidget::mouseReleaseEvent ( QMouseEvent * e )36: {37: if (!mWasMouseClicking) )38: {39: return ;40: }41:42: if ( CheckIfPointInWidget (e->pos()) == false )43: {44: mWasMouseClicking = false ;45: return ;46: }47:48: if ( Abs ( DistanceBetweenpoints (e->pos() , m_lastPoint) > 4 == true )49: {50: mWasMouseClicking = false ;51: return ;52: }53: emit OnMouseClick (e->pos());54: }
Sources:
http://www.youtube.com/watch?v=ScZn-cQiVFs&list=SP2D1942A4688E9D63
http://www.developer.nokia.com/Community/Wiki/MouseClick_event_in_Qt's_custom_widget
http://www.qtcentre.org/threads/19493-creating-custom-signa
http://harmattan-dev.nokia.com/docs/library/html/qt4/qbrush.html
אין תגובות:
הוסף רשומת תגובה