2013-05-13 75 views
1

奇怪的事情發生:我需要在標籤上使用rubberBand。 這裏是我的代碼:QRubberBand在確定的標籤上

QRubberBand *rubberBand; 
    QPoint mypoint; 

void MainWindow::mousePressEvent(QMouseEvent *event){ 

    mypoint = event->pos(); 
    rubberBand = new QRubberBand(QRubberBand::Rectangle, ui->label_2);//new rectangle band 
    rubberBand->setGeometry(QRect(mypoint, ui->label_2->size())); 
    rubberBand->show(); 
} 

void MainWindow::mouseMoveEvent(QMouseEvent *event){ 
    rubberBand->setGeometry(QRect(mypoint, event->pos()).normalized());//Area Bounding 
} 

void MainWindow::mouseReleaseEvent(QMouseEvent *event){ 
    rubberBand->hide();// hide on mouse Release 
    rubberBand->clearMask(); 
} 

一切正常,但只有一個麻煩 - rubberBound開始畫下那麼一點點coursor周圍設置100-150px。

我在做什麼錯?

回答

1

event->pos()與您的標籤和橡皮圈的座標系不同。

http://qt-project.org/doc/qt-4.8/qwidget.html#mapFrom

http://qt-project.org/doc/qt-4.8/qwidget.html#mapFromGlobal

http://qt-project.org/doc/qt-4.8/qwidget.html#mapFromGlobal

http://qt-project.org/doc/qt-4.8/application-windows.html

http://qt-project.org/doc/qt-4.8/qwidget.html#geometry-prop

http://qt-project.org/doc/qt-4.8/qwidget.html#rect-prop

您需要將event->pos()映射到不同的座標系中以補償偏移量。

編輯:這裏是一個例子。

// In your constructor set rubberBand to zero. 
rubberBand = 0; 

void MainWindow::mousePressEvent(QMouseEvent *event){ 

    mypoint = ui->label->mapFromGlobal(this->mapToGlobal(event->pos())); 
    // mypoint = ui->label->mapFrom(this, event->pos()); 
    // mypoint = this->mapTo(ui->label, event->pos()); 
    if(rubberBand == 0) // You should add this to not have a memory leak 
     rubberBand = new QRubberBand(QRubberBand::Rectangle, ui->label_2);//new rectangle band 
    rubberBand->setGeometry(QRect(mypoint, ui->label_2->size())); 
    rubberBand->show(); 
} 

QRubberBand說明它顯示瞭如果有人正在對他們mouseEvents被觸發與小部件中使用它會被執行。由於您在與其他窗口小部件鼠標事件不同的窗口小部件上使用它,因此必須映射座標。

希望有所幫助。

+0

謝謝,但我仍然不明白我應該如何將coords從mainWindow轉換爲我的標籤 – tema 2013-05-13 17:07:54