QtWidget 實(shí)現(xiàn)不規(guī)則窗體與按鈕
QWidget有很多成員函數(shù),但是它們中的一些有少量的直接功能:例如,QWidget有一個(gè)字體屬性,但是它自己從來(lái)不用。有很多繼承它的子類提供了實(shí)際的功能,比如QPushButton、QListBox和QTabDialog等等。
關(guān)鍵是使用
- void QWidget::setMask ( const QBitmap & bitmap )
- void QWidget::setMask ( const QRegion & region )
- void QWidget::setMask ( const QRegion & region )
- Causes only the parts of the widget which overlap region to be visible.
只有widget與region重疊的地方才會(huì)顯示出來(lái). 自己構(gòu)造一個(gè)QRegion就行了.
- void ShapedClock::resizeEvent(QResizeEvent * /* event */) {
- int side = qMin(width(), height());
- QRegion maskedRegion(width() / 2 - side / 2, height() / 2 - side / 2, side,
- side, QRegion::Ellipse);
- setMask(maskedRegion);
- }
void QWidget::setMask ( const QBitmap & bitmap )
Causes only the pixels of the widget for which bitmap has a corresponding 1 bit to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform.
只有在bitmap中像素?cái)?shù)據(jù)是1的地方才會(huì)顯示出widget的相應(yīng)像素來(lái). Bitmap就是像素?cái)?shù)據(jù)只有兩個(gè)值: 0和1 (1 bit-depth, monochrome).
- QLabel topLevelLabel;
- QPixmap pixmap(":/images/tux.png");
- topLevelLabel.setPixmap(pixmap);
topLevelLabel.setMask(pixmap.mask()); // 可以不使用轉(zhuǎn)換的, 使用一張專門的bitmap圖片.上面的這些方式用一普通的QWidget就可以了. 當(dāng)然, 對(duì)于窗口而言, 很多時(shí)候我們要把它的標(biāo)題欄去掉:widget->setWindowFlags(Qt::FramelessWindowHint);但是對(duì)于不規(guī)則的QPushButton就有些特殊, 要使用QIcon來(lái)處理:
- button->setIcon(QIcon("xxx.png"));
- button->setIconSize(w, h);
- button->setMask(maskBitmap/*maskedRegion*/);
- button->setFixedSize(w, h); // 這個(gè)當(dāng)然最好使用它的icon的大小.
小結(jié):QtWidget 實(shí)現(xiàn)不規(guī)則窗體與按鈕的內(nèi)容介紹完了,編程的友人們總是喜歡做些比較炫的效果,QtWidget幫了我們的大忙!最后希望本文對(duì)你有幫助。