How to subclass a control?
-
.h
class MainWindow: public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindowClass ui; } class Mybutton : public QToolButton { public: Mybutton() { }; QToolButton* Test(QWidget* parent = 0); protected: virtual void paintEvent(QPaintEvent* pQEvent) override; };
.cpp
QToolButton* Mybutton::Test(QWidget* parent) { QToolButton* newbtn = new QToolButton(parent); return newbtn; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); Mybutton my; QToolButton* newbtn = my.Test(this); newbtn->setGeometry(222, 222, 110, 70); } void Mybutton::paintEvent(QPaintEvent* pQEvent) { qDebug() << "test" << "\n"; }
The function
Mybutton::paintEvent
isn't getting called. -
@Cesar said in How to subclass a control?:
got it working.
I assume it looks a lot different to what you originally posted.
Do subclassing controls increase my GUI CPU usage?
No
is desirable to avoid subclass or is it 'ok'?
No. If you need to subclass then do so.
-
Hi @Cesar,
The function Mybutton::paintEvent isn't getting called.
Sounds like you figured it out, but in case others come across the same topic, the problem is that while
Mybutton
inheritsQToolButton
,Mybutton::Test()
is returning a newQToolButton
that does not.Instead of:
class Mybutton : public QToolButton { public: Mybutton() { }; QToolButton* Test(QWidget* parent = 0); ....
do:
class Mybutton : public QToolButton { public: Mybutton(QWidget * parent = 0) : QTootlButton(parent) { }; // QToolButton* Test(QWidget* parent = 0); // You don't need this one.
Then, in
MainWindow::MainWindow()
, instead of:QToolButton* newbtn = my.Test(this);
do this:
QToolButton* newbtn = new Mybutton(this); // or Mybutton * newbtn = new Mybutton(this);
And yes, as @ChrisW67 said, it is ok to sub-class widgets - indeed, I'd say its recommended :)
Cheers.
-
@Paul-Colby is possible to save the content drawn in the painter to when the function is called again avoid doing all process again?
-
is possible to save the content drawn in the painter to when the function is called again avoid doing all process again?
Well QPicture can do that.
You can also render to a picture and only draw the picture.however, this is only used if the QPainter part is truly heavy.
Not just for a perceived optimization.