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.
{
Q_OBJECT
public:
explicit MyMainWindow
(QWidget * parent
= 0) {
;
}
protected:
{
p.drawRect(event->rect().adjusted(10, 10, -10, -10));
}
};
int main(int argc, char ** argv)
{
MyMainWindow m;
// QComboBox * comboBox = new QComboBox;
// comboBox->addItems(QStringList() << "One" << "Two" << "Three" << "Four");
// m.setCentralWidget(comboBox);
m.show();
return app.exec();
}
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();
}
To copy to clipboard, switch view to plain text mode
Bookmarks