Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The simpler way as mentioned by <a href="https://stackoverflow.com/users/307339/stephen-chu">@Stephen Chu</a> is using <a href="http://qt-project.org/doc/qt-4.8/qgraphicsscene.html" rel="nofollow noreferrer"><code>QGraphicsScene</code></a>.</p> <p>Here is an example that prints with qdebug when you click on a rectangle.</p> <p><strong>clickrect.hpp</strong></p> <pre><code>#ifndef _HANDLER_HPP_ #define _HANDLER_HPP_ #include &lt;QtGui&gt; class ClickRect : public QGraphicsRectItem { public: ClickRect( const QRect&amp; rect, const QColor&amp; color, const QString&amp; name, QGraphicsItem* parent = 0); protected: virtual void mousePressEvent(QGraphicsSceneMouseEvent* event); private: QString mName; }; #endif </code></pre> <p><strong>clickrect.cpp</strong></p> <pre><code>#include "clickrect.hpp" ClickRect::ClickRect( const QRect&amp; rect, const QColor&amp; color, const QString&amp; name, QGraphicsItem* par ) : QGraphicsRectItem(rect, par), mName(name) { setBrush(QBrush(color)); } void ClickRect::mousePressEvent(QGraphicsSceneMouseEvent* ev) { qDebug() &lt;&lt; mName; } </code></pre> <p><strong>test.cpp</strong></p> <pre><code>#include &lt;QtGui&gt; #include "clickrect.hpp" int main(int argc, char** argv) { QApplication app(argc, argv); QGraphicsScene scene; QGraphicsView view(&amp;scene); view.show(); ClickRect rect_a(QRect(0, 0, 30, 30), QColor("#FDD"), "A"); ClickRect rect_b(QRect(40, 0, 30, 30), QColor("#DFD"), "B"); scene.addItem(&amp;rect_a); scene.addItem(&amp;rect_b); return app.exec(); } </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.8) find_package(Qt4 4.8 REQUIRED QtCore QtGui) include(${QT_USE_FILE}) add_executable(test test.cpp clickrect.hpp clickrect.cpp ${MOC_FILES}) target_link_libraries(test ${QT_LIBRARIES}) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload