PDA

View Full Version : Using QPainter in MainWindow



aaditya190
9th December 2013, 08:04
I explored various examples of QPainter wherein it is used by separate classes to draw objects. I wish to use QPainter in the Mainwindow itself to draw rectangles. Is it possible to do so? If yes, Can anyone help me with it?

Santosh Reddy
9th December 2013, 09:49
I wish to use QPainter in the Mainwindow itself to draw rectangles. Is it possible to do so?
Well technically QMainWindow is a QWidget so you can use QPainter, but you will either have to sacrifice some features which QMainWindow provides (like dock, menu, toolbars, etc) or have to come up with a way to put your rectangle painting over or below the QMainWindow painting. Either ways it is not trival.

If you just need to draw some rectangles, you better draw them on a custom QWidget and put that widget as central widget of the mainwindow.


If yes, Can anyone help me with it?
It is very similar to how you do it with a QWidget. Here is an example, run it as is you can see the rectangle on mainwindow, and then un-comment the code in main() and see the combox will be added to mainwidget and rectangle is not visible, this is because child widgets are draw over the parent widget.


class MyMainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MyMainWindow(QWidget * parent = 0)
: QMainWindow(parent)
{
;
}

protected:
void paintEvent(QPaintEvent * event)
{
QMainWindow::paintEvent(event);

QPainter p(this);
p.setPen(QColor(Qt::red));
p.drawRect(event->rect().adjusted(10, 10, -10, -10));
}
};

int main(int argc, char ** argv)
{
QApplication app(argc, argv);

MyMainWindow m;
// QComboBox * comboBox = new QComboBox;
// comboBox->addItems(QStringList() << "One" << "Two" << "Three" << "Four");
// m.setCentralWidget(comboBox);
m.show();

return app.exec();
}

anda_skoa
9th December 2013, 10:35
If you just need to draw some rectangles, you better draw them on a custom QWidget and put that widget as central widget of the mainwindow.


I would recommend you follow that suggestion instead of interfering with QMainWindow's internals

Cheers,
_