MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); ln = new Line(ui->widget, 10, 20, 50, 500); ui->widget->setAttribute(Qt::WA_OpaquePaintEvent); ui->widget->show();}
class Line : public QWidget{ Q_OBJECT qreal x1, y1, x2, y2;public: explicit Line(QWidget *parent, qreal px1, qreal py1, qreal px2, qreal py2); void draw(QPainter *painter);protected: void paintEvent(QPaintEvent *);signals: public slots: };
Line::Line(QWidget *parent, qreal px1, qreal py1, qreal px2, qreal py2) : QWidget(parent), x1(px1), y1(py1), x2(px2), y2(py2){} void Line::paintEvent(QPaintEvent *){ QPainter painter(this); draw(&painter);} void Line::draw(QPainter *painter){ painter->setPen(QPen(Qt::red, 1, Qt::SolidLine)); qreal x_cur = x1, y_cur = y1; while( x_cur != x2 || y_cur != y2 ) { painter->drawPoint(QPointF(x_cur, y_cur)); if (x_cur != x2) { if (x_cur < x2) ++x_cur; else --x_cur; } if (y_cur != y2){ if (y_cur < y2) ++y_cur; else --y_cur; } }}
ln = new Line(centralWidget(), 10, 10, 10, 500);
ln = new Line(ui->widget, 10, 10, 50, 500);QLayout *layout = ln->layout();
C++ (Qt)MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); ln = new Line(ui->widget, 10, 20, 50, 500); QVBoxLayout * layout = new QVBoxLayout (); layout->addWidget(ln); ui->widget->setLayout( layout ); ui->widget->setAttribute(Qt::WA_OpaquePaintEvent); ui->widget->show();}