4
votes

First of all, thanks for you time reading my question.

I created my own Qt Widget (parent of QWidget) and has a QImage "inside" to manipulate images. The problem I have is the following: when I promote the content of a QScrollArea (QDesigner) to my widget, the scroll features doesn't works; I haven't any scroll bar or I can't see any result when I use the method 'ensureVisible(..)'.

Please can you tell me if I need to overload or override any method in my own widget.

Regards and thanks in advance, Oscar.


Code: The intention is use directly myWidget (promoting it in QDesigner) and I don't use directly a QImage 'cos I want to save some extra data in the widget.

struct myData
{
    QImage myImage;
};

myWidget::myWidget(QWidget* parent, Qt::WFlags fl) : QWidget(parent, fl)
{
    myData = new myData();
}

myWidget::~myWidget()
{
    delete myData;
}

void myWidget::init(QImage image)
{
    try
    {
        myData->myImage = image;
        resize(myData->myImage->width, myData->myImage->height);
    }
    catch(...)
    {
        QString msg("myWidget::init return error\n");
        qWarning(msg.toLatin1().data());
        return;
    }
}

QSize myWidget::minimumSize() const {
    return myData->myImage.size();
}

QSize myWidget::sizeHint() const {
    return myData->myImage.size();
}

void myWidget::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    painter.drawImage(myData->myImage.rect(), myData->myImage);
}

void myWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        emit mousePress(event->x(), event->y());
    }
}

void myWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::RightButton) {
        emit mouseMove(event->x(), event->y());
    }
}
1
I think you need add some code to your question...mosg
@mosg the code of the widget is available. Thanks for your suggestion.osanchezmon

1 Answers

1
votes

I've something like this a few times and it can be confusing getting all the signaling correct. First, take a look at the Image Viewer Example. It will probably answer most of your questions. There are two key sections to look at. First is the scaling code -

 void ImageViewer::scaleImage(double factor)
 {
     Q_ASSERT(imageLabel->pixmap());
     scaleFactor *= factor;
     imageLabel->resize(scaleFactor * imageLabel->pixmap()->size());

     adjustScrollBar(scrollArea->horizontalScrollBar(), factor);
     adjustScrollBar(scrollArea->verticalScrollBar(), factor);

     zoomInAct->setEnabled(scaleFactor < 3.0);
     zoomOutAct->setEnabled(scaleFactor > 0.333);
 }

Then, the scrollbars have to be adjusted. That code is -

     void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor)
 {
     scrollBar->setValue(int(factor * scrollBar->value()
                             + ((factor - 1) * scrollBar->pageStep()/2)));
 }

I've found this sample code solved about 75% of my problems when trying to anything with an image inside of a scroll area.