Insane CPU usage in QT 5.0

Posted by GravityScore on Stack Overflow See other posts from Stack Overflow or by GravityScore
Published on 2013-07-03T11:03:04Z Indexed on 2013/07/03 11:05 UTC
Read the original article Hit count: 280

Filed under:
|
|
|
|

I'm having trouble using the QT framework, particularly with the paintEvent of QWidget. I have a QWidget set up, and am overriding the paintEvent of it. I need to render a bunch of rectangles (grid system), 51 by 19, leading to 969 rectangles being drawn. This is done in a for loop. Then I also need to draw an image on each on of these grids. The QWidget is added to a QMainWindow, which is shown.

This works nicely, but it's using up 47% of CPU per window open! And I want to allow the user to open multiple windows like this, likey having 3-4 open at a time, which puts the CPU close to 150%.

Why does this happen? Here is the paintEvent contents. The JNI calls don't cause the CPU usage, commenting them out doesn't lower it, but commenting out the p.fillRect and Renderer::renderString (which draws the image) lowers the CPU to about 5%.

// Background
QPainter p(this);
p.fillRect(0, 0, this->width(), this->height(), QBrush(QColor(0, 0, 0)));

// Lines
for (int y = 0; y < Global::terminalHeight; y++) {
    // Line and color method ID
    jmethodID lineid = Manager::jenv->GetMethodID(this->javaClass, "getLine", "(I)Ljava/lang/String;");
    error();
    jmethodID colorid = Manager::jenv->GetMethodID(this->javaClass, "getColorLine", "(I)Ljava/lang/String;");
    error();

    // Values
    jstring jl = (jstring) Manager::jenv->CallObjectMethod(this->javaObject, lineid, jint(y));
    error();
    jstring cjl = (jstring) Manager::jenv->CallObjectMethod(this->javaObject, colorid, jint(y));
    error();

    // Convert to C values
    const char *l = Manager::jenv->GetStringUTFChars(jl, 0);
    const char *cl = Manager::jenv->GetStringUTFChars(cjl, 0);
    QString line = QString(l);
    QString color = QString(cl);

    // Render line
    for (int x = 0; x < Global::terminalWidth; x++) {
        QColor bg = Renderer::colorForHex(color.mid(x + color.length() / 2, 1));

        // Cell location on widget
        int cellx = x * Global::cellWidth + Global::xoffset;
        int celly = y * Global::cellHeight + Global::yoffset;

        // Background
        p.fillRect(cellx, celly, Global::cellWidth, Global::cellHeight, QBrush(bg));

        // String
        // Renders the image to the grid
        Renderer::renderString(p, tc, text, cellx, celly);
    }

    // Release
    Manager::jenv->ReleaseStringUTFChars(jl, l);
    Manager::jenv->ReleaseStringUTFChars(cjl, cl);
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about qt