我需要在作为mainWindow的子项的小部件上绘制矩形。但是下面的代码在绘制Widget时没有成功,它是在父屏幕上绘制的。
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::paintEvent (QPaintEvent *e)
{
QPainter *painter = new QPainter (ui->widget);
painter->begin (this);
painter->drawRect(e->rect());
painter->end ();
}
void MainWindow::mouseMoveEvent(QMouseEvent *event){
update((QRect(LastPoint,event->pos())));
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
LastPoint = event->pos();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
mainwindow.hpp
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void paintEvent (QPaintEvent *e);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
QPoint LastPoint;
~MainWindow();
private:
Ui::MainWindow *ui;
};
我附上了设计师的截图。