Reputation: 355
I have a program and I am attempting to draw a line on a widget. Here is the code that I have:
header:
#include <QWidget>
#include <QtWidgets>
class DrawingWidget : public QWidget{
Q_OBJECT
public:
explicit DrawingWidget(QWidget *parent = 0);
~DrawingWidget();
QSize minimumSizeHint() const;
QSize sizeHint() const;
protected:
void paintEvent(QEvent *);
}
I also have a slot in the actual program, but at the moment it is commented out while I try to find this bug.
The Code:
DrawingWidget::DrawingWidget(QWidget *parent) : QWidget(parent){
update();
}
DrawingWidget::~DrawingWidget(){
}
QSize DrawingWidget::minimumSizeHint() const{
return QSize(50,30);
}
QSize DrawingWidget::sizeHint() const{
return QSize(150,50);
}
void DrawingWidget::paintEvent(QEvent *){
qDebug() << "paint event called";
QPainter(this);
QPen drawPen(Qt::black, 3);
QPoint leftLinePoint(10,20);
QPoint rightLinePoint(50,20);
painter.setPen(drawPen);
painter.drawLine(leftLinePoint, rightLinePoint);
}
This widget is included in another program, which has the following constructor:
DataDisplayWidget::DataDisplayWidget(QWidget *parent) : QWidget(parent){
//other unrelated code
displayBox = new QGroupBox("Lines");
QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::LeftToRight);
QGridLayout *displayLayout = new QGridLayout;
myWidget = new DrawingWidget;
displayLayout->addWidget(myWidget);
displayBox->setLayout(displayLayout);
//add other things to main layout
mainLayout->addWidget(displayBox);
setLayout(mainLayout);
}
The DisplayDataWidget is then used in the main window, which has the following code:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent){
//a bunch of unrelated constructor code
createDataDisplayWidget();
//more unrelated code
}
void MainWindow::createDataDisplayWidget(){
DataDisplayWidget *thisWidget = new DataDisplayWidget;
QDockWidget *dock = new QDockWidget("Displayed Data", this);
dock->setWidget(thisWidget);
dock->setAllowedAreas(Qt::BottomDockWidgetArea);
addDockWidget(Qt::BottomDockWidgetArea, dock);
//connections
}
So, a brief summary. I have my program which starts from main.cpp, and launches a QMainWindow object. This QMainWindow object then creates a dock widget, which includes another widget, which includes my drawing widget. From testing the drawing widget code in another program (which is working), the actual drawing of lines should run just fine and draw a black line that is visible on the screen. However, in testing with this program, I never get the line, nor do I get the debug message "paint event called".
What am I missing to be able to get the paintEvent triggered?
Upvotes: 0
Views: 1043
Reputation: 8994
You typed a wrong signature. You need void paintEvent( QPaintEvent *e );
. It is good practice to use an override
keyword to prevent such errors.
Upvotes: 4