• you only need one painter. the second one wasn't activated, and you don't need it anyway.

  • don't ever call repaint() unless you somehow absolutely need the painting to be done before repaint() returns (that's what happens!). if you keep the event loop running properly, you won't ever need that.

  • don't call update() from paintevent() : it's nonsense (literally).

  • when you wish to repaint the widget, call update() : it schedules an update from the event loop. multiple outstanding updates are coalesced to keep the event loop functional and prevent event storms.

  • let the compiler generate even more memory management code for you. you've done the first step by using smart pointers - that's good. now do the second one: hold the instance of customwidget by value. it doesn't have to be explicitly dynamically allocated. c++ is not c, you can leverage values.

  • in a simple test case, you don't want three files. your code should fit in as few lines as possible, in a single main.cpp . if you need to moc the file due to q_object macros, add #include "main.moc" at the end, and re-run qmake on the project to take notice of it.

  • this is how such a test case should look, after fixing the problems. remember: it's a test case, not a 100kloc project. you don't need nor want the meager 35 lines of code spread across three files. moreover, by spreading out the code you're making it harder for yourself to comprehend.

    even in big projects, unless you can show significant build time improvements if doing the contrary, you can have plenty of small classes implemented java-style completely in the header files. that's about the only java-style-anything that belongs in c++.

    // https://github.com/kubao/stackoverflown/tree/master/questions/simple-paint-38796140
    #include <qtwidgets>
    class customwidget : public qwidget
       qpoint m_mousepos;
    public:
       explicit customwidget(qwidget *parent = nullptr) : qwidget{parent} {}
       void paintevent(qpaintevent *) override;
       void mousemoveevent(qmouseevent *event) override {
          m_mousepos = event->pos();
          update();
    void customwidget::paintevent(qpaintevent *)
       qpainter painter(this);
       auto r1 = rect().adjusted(10, 10, -10, -10);
       painter.setpen(qt::white);
       painter.drawrect(r1);
       auto r2 = qrect{qpoint(0, 0), qsize(100, 100)};
       r2.movecenter(m_mousepos);
       painter.setpen(qpen{qt::black, 3, qt::solidline, qt::squarecap, qt::miterjoin});
       painter.drawrect(r2);
    int main(int argc, char ** argv) {
       qapplication app{argc, argv};
       customwidget w;
       w.show();
       return app.exec();
                                            
  • "QPainter::drawRects: Painter not active " error C++/QT
  • QtPainter Error Paint device returned engine ==0, type 3 ,Painter not active
  • "X does not name a type" error in C++
  • How to fix the error "Windows SDK version 8.1" was not found?
  • 'uint32_t' identifier not found error
  • Identifier not found error on function call
  • C++ Error 'nullptr was not declared in this scope' in Eclipse IDE
  • File not recognized: File truncated GCC error
  • c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)
  • "string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)
  • Class method and variable with same name, compile error in C++ not in Java?
  • error C2039: 'string' : is not a member of 'std', header file problem
  • How to fix Genymotion in linux ElementaryOS with error `CXXABI_1.3.8' not found
  • 'was not declared in this scope' error
  • error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup, but this time it's NOT a Windows/Console problem!
  • Error message: "setw is not defined" using g++
  • std::thread error (thread not member of std)
  • Error enabling openmp - "ld: library not found for -lgomp" and Clang errors
  • 'X is not a template' error
  • Eclipse c++ Type could not be resolved error even though build is successful
  • Why is it not a compiler error to assign to the result of a substr call?
  • OpenCV GTK+2.x error - "Unspecified error (The function is not implemented...)"
  • Compiler error C2653: not a class or namespace name
  • Generating an error if checked boolean macro is not defined
  • gdb error not in executable format: File format not recognized
  • build error with c++ - ‘find_if’ is not a member of ‘std'
  • "Program is not a recognized executable" error in Eclipse
  • Error with gcc but not with clang when compiling initializer list containing pointers to template function
  • Why am I getting the error 'A<int>' is not an accessible base of 'S<int>' for a base class's base class?
  • Why is 'int x = + "foo";' a type error but not a syntax error?
  • More Query from same tag

  • Converting hex string to unsigned int issue C++
  • Optimizing Linux Socket
  • How to save a directed acyclic graph to disk?
  • Using NDK from C++ updating Android UI
  • How to get system environment variables using boost library?
  • Will accessing a class object through a pointer to its derived class break strict aliasing rules?
  • MSVC error when using capture-less lambda expressions as second and third operand of conditional operator
  • The best method to send images interactively from Haskell backend to Qt QUI
  • How do I turn off the gcc preprocessor on linux?
  • Insert content in static containers of a templated class prior to main
  • QML view wont update when adding a new item to a QAbstractListModel based model
  • Pass struct* from c# to c++ dll
  • Why does a random extra letter appearing in my functions name?
  • getaddrinfo calls assert in the program
  • Naive Primality Testing Optimization
  • print a matrix through a pointer
  • Travel from a point A to all remaining points via nearest neighbor point first
  • How to sort vector of objects by a private string variable alphabetically
  • Unable to set Java int array field from JNI
  • Does Visual Studio C/C++ support automatic software prefetching?
  • Using a type that depends on lambda function as a return type
  • Returning by value to rvalue reference
  • Porting C++ OpenGL Game to iPad
  • Inner if statement kills vectorization
  • Function argument type
  • Why is my overloaded template function is promoting to const differently then a non-template function.
  • boost::asio::tcp::socket Close and cancel without handlers being called
  • Template function overload resolution
  • In C++, how to overload a binary operator in a derived class?
  • is any difference between std::forward<T> and std::forward<decltype(t)>?
  •