0

This is a very very simple question I think for qt developers.

I have a very large code (I didn't write) that uses qt for drawing, and I just created a on_actionSomething_toggled(bool checked) I want it to draw some geometric stuff.

I will just be happy if you could tell me how to get to draw a line (inside that method), I could later draw whatever I want with those lines.

I already tried:

void 
MainWindow::on_actionSomething_toggled(bool checked){
  QPainter pa(this);
  pa.drawLine(20, 40, 250, 40);
}

But it says:

QPainter::begin: Widget painting can only begin as a result of a paintEvent

So I just want to know how to draw a simple line inside my on_actionSomething_toggled method, or maybe I am doing it everything wrong, and how could I simply add this drawing line functionality inside that big code I have.

4

3 回答 3

2

就像警告消息所说的那样,通常使用 QPainter 绘制事物的唯一合适时间是从 paintEvent() 方法内部。

所以通常的方式来做你想做的事是这样的:

1)当你想画一条线时,设置一个成员变量来记住你想要画的线(例如this->draw_the_line = true;)

2) 将 draw_the_line 设置为其新值后,在要绘制线条的小部件上调用 update() ...这将告诉 Qt 尽快安排对该小部件上的 paintEvent() 的调用。

3) 重新实现小部件的paintEvent() 方法,如下所示:

void MyWidgetSubclass :: paintEvent(QPaintEvent * e)
{
   TheWidgetSuperclass::paintEvent(e);  // this will draw the widget's usual graphics

   // Plus your custom stuff on top, if appropriate
   if (this->draw_the_line) 
   {
      QPainter p(this);
      p.drawLine(20,40,250,40);
   }
}

请注意,为了做到这一点,您必须对小部件进行子类化(以便您可以在子类中实现您自己的 paintEvent() 版本,它将被调用而不是通常的 paintEvent() 方法)——如果你没有t 已经这样做了。

于 2013-07-09T03:47:22.250 回答
0

您应该使用图形视图框架。它在内部管理绘画。您在插槽中唯一需要做的就是:

scene->addLine(20, 40, 250, 40);
于 2013-07-09T08:41:43.317 回答
0

正如警告消息所说,在小部件上绘图只能从绘制事件内部发生。

实现您想要的一种方法是首先在QPixmap上绘制,向小部件发送更新通知,然后让绘制事件处理程序绘制该像素图。

另一种可能更简单、更优雅的方法是在QPainterPath中准备绘制操作。然后,您在小部件的绘制事件处理程序中绘制它。

两种方式都假设您已经通过覆盖QWidget::paintEvent(QPaintEvent*)实现了自己的绘制事件处理程序。

于 2013-07-09T03:49:05.350 回答