Reputation: 415
I want to dynamically create a child widget on the click of the mouse. When I manually create it in ctor, everything is ok.
Foo::Foo(QWidget *partent) : QWidget(parent)
{
auto *txt{ new QPlainTextEdit(this) };
}
but when I do the same in mousePressEvent, it doesn't appear.
Foo::mousePressEvent(QMouseEvent *event)
{
auto *txt{ new QPlainTextEdit(this) };
QWidget::mousePressEvent(event);
}
What might be the problem? Is there something in the ctor that triggers the appearance of the widget?
UPD: adding the full code, as asked in the comments.
// foo.h
#include <QMouseEvent>
#include <QWidget>
class Foo : public QWidget
{
Q_OBJECT
public:
explicit Foo(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *event) override;
}
// main.cpp
#include "foo.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Foo w;
w.show();
return a.exec();
}
Upvotes: 1
Views: 56
Reputation: 3883
As I understand from your question , I write this example for you :
My example has MainWindow , and in
mainwindow.h
#include <QMainWindow>
#include <QPlainTextEdit>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
// QWidget interface
protected:
void mousePressEvent(QMouseEvent *event);
private:
QPlainTextEdit *_text;
};
and in mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
_text = new QPlainTextEdit(this);
_text->setGeometry(event->x(),event->y(),_text->width(),_text->height());
_text->setPlainText("Hello World");
_text->show();
}
Anywhere on the Window , when you press the mouse one QPlainTextEdit whit Hello World text appears.
the out put is :
Upvotes: 1