c++ - GUI 应用程序中的 QPainter 错误

标签 c++ user-interface qt4

我正在尝试编写一个 GUI,用 C++ 在其上绘制图形。我得到了一个错误列表,所有错误都说: “QPainter::begin:Widget 绘画只能作为 paintEvent 的结果开始” 似乎没有任何东西在绘画。

main.cpp

#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <iostream>

using namespace std;

#include "skewNormal.h"
#include "ui.h"

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    Window w;
    #if defined(Q_OS_SYMBIAN)
    w.showMaximized();
    #else
    w.show();
    #endif
    return app.exec();
}

ui.h

#ifndef UI_H_INCLUDED
#define UI_H_INCLUDED
#include <QtGui/QMainWindow>

class Window : public QWidget
{
    public:
    Window();

    void paintEvent ( QPaintEvent * event );
};



#endif // UI_H_INCLUDED

ui.cpp

#ifndef GRAPHPN3670_H
#define GRAPHPN3670_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QPaintEvent>
#include <QtGui/QGraphicsView>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QWidget>
#include <QtCore/QRect>
#include <iostream>

using namespace std;

#include "ui.h"
#include "skewNormal.h"

Window::Window()
{
    cout<<"Hello1";
}

void Window::paintEvent ( QPaintEvent * event ){
    cout<<"Hello from paint event";
    QPainter p(this);
    int xL = -width() / 2;
    int yL = 0;
    for(int x = -width() / 2; x < width() / 2; x++)
    {
        int y = getSkewNormal(0.5, x);
        p.drawLine(xL + width() / 2, height() - yL, x + width() / 2, height() - y);
        xL = x;
        yL = y;
    }
}

#endif // GRAPHPE3488_H

最佳答案

来自Qt documentation :

Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent(); that is unless the Qt::WA_PaintOutsidePaintEvent widget attribute is set. On Mac OS X and Windows, you can only paint in a paintEvent() function regardless of this attribute's setting.

关于c++ - GUI 应用程序中的 QPainter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297845/

相关文章:

c++ - 如何尝试读取为 int,如果失败则读取为字符串?

c++ - 无法编译 Hello Web 服务客户端

c++ - QT多线程和更新GUI

c++ - Qt for Nokia 中的样式表

c++ - Qt声子媒体对象错误

c++ - 列数。 QMYSQLResult::data: 列超出范围

C++/GLFW - 使用 Mutex 对象的正确方法?

c++ - 在 C、C++ 中检测 Windows 或 Linux

java - 无法正确对齐 UI 项目

java - 从文件中读取并在 textarea java 中显示