QPainter or QLabel is less costly to draw QPixmap

2019-07-20 08:16发布

问题:

I have to create an Icon pixmap, two methods I am familiarized to do that, One is setting the pixmap as o QLabel and display it, and other is drawing pixmap using QPainter, ie

Method one

Icon::Icon
{
    QLabel iconLab = new QLabel;
    QLabel iconName = new QLabel;
    iconLab->setPixmap("mypixmap.png"); 
    iconName->setText("myiconname");
    QVBoxLayout *iconLayout = new QVBoxLayout; 
    iconLayout->setMargin(0);
    iconLayout->addWidget(iconLab, 1, Qt::AlignCenter);
    iconLayout->addWidget(iconName, 1, Qt::AlignCenter);
    iconLayout->setSpacing(0);

    setLayout(iconLayout);
    setMaximumSize(100,160);
    setMinimumSize(100,160);
}

Method 2,

Icon::Icon
{     
    setMaximumSize(100,160);
    setMinimumSize(100,160);
}
Icon::paintEvent(QPaintEvent*)
{      
    QPainter painter;
    painter.drawPixmap(0,0,myPixmap);
    painter.drawText(0,100,myText)
}

I have to draw number of Icons, more than 100, so which one is effective, Thanks in advance,

回答1:

From a theoretical perspective, the QPainter approach will be faster because the overhead introduced by QLabel is avoided. Internally QLabel needs to use a QPainter as well (using drawPicture()).

However, it is questionable if this difference will make your application more responsive. I doubt that this optimization will even be noticeable.

I would recommend to take care of code readability in the first place and take what is easier / feels better to use.

Once you have the functionality in place and there is a performance problem, you can start profiling and decide where the time and effort to optimize is best invested.



回答2:

If you have to draw more than 100 of this, this usually means that you should not use any of those solutions.
Most probably QListView with custom delegate and QAbstractListModel to hold those images is what you really need (or table version).