一、前言

進入智慧手機時代以來,各種各樣的APP大行其道,手機上面的APP有很多流行的元素,開關按鈕個人非常喜歡,手機QQ、360衛士、金山毒霸等,都有很多開關控制一些操作,在WINFORM專案上,如果將CheckBox也改為開關按鈕,估計也會為專案增添不少新鮮感。 沿襲之前的做法,本人還是喜歡直接PS好圖片後,用drawimage方法將圖片繪製到使用者控制元件上,啟用雙緩衝和背景透明,有些人說PS一張精美的圖片也不是很容易,需要專業的,這裡提供一個好方法,讓你也可以獲取到這些圖片,其實大部分的APP都可以用解壓軟體開啟,拓展名改為。zip即可,解壓出來一般裡面都含有絕大部分的圖片,發現絕大部分的APP都喜歡用圖片作為背景來展示一些效果,而不是原原本本的用程式碼一點點繪製。騰訊就是騰訊啊,大公司!人家的美工MM設計的圖片那真的沒得話說,絕對一流,手機QQ每次升級一個版本,都會下過來將裡面的精美圖片圖示之類的提取出來,以便專案使用,這不會算是盜版吧!

二、程式碼思路

ImageSwitch

::

ImageSwitch

QWidget

*

parent

QWidget

parent

{

isChecked

=

false

buttonStyle

=

ButtonStyle_2

imgOffFile

=

“:/image/btncheckoff2。png”

imgOnFile

=

“:/image/btncheckon2。png”

imgFile

=

imgOffFile

}

void

ImageSwitch

::

mousePressEvent

QMouseEvent

*

{

imgFile

=

isChecked

imgOffFile

imgOnFile

isChecked

=

isChecked

this

->

update

();

}

void

ImageSwitch

::

paintEvent

QPaintEvent

*

{

QPainter

painter

this

);

painter

setRenderHints

QPainter

::

SmoothPixmapTransform

);

QImage

img

imgFile

);

img

=

img

scaled

this

->

size

(),

Qt

::

KeepAspectRatio

Qt

::

SmoothTransformation

);

//按照比例自動居中繪製

int

pixX

=

rect

()。

center

()。

x

()

-

img

width

()

/

2

int

pixY

=

rect

()。

center

()。

y

()

-

img

height

()

/

2

QPoint

point

pixX

pixY

);

painter

drawImage

point

img

);

}

bool

ImageSwitch

::

getChecked

()

const

{

return

isChecked

}

ImageSwitch

::

ButtonStyle

ImageSwitch

::

getButtonStyle

()

const

{

return

this

->

buttonStyle

}

QSize

ImageSwitch

::

sizeHint

()

const

{

return

QSize

87

28

);

}

QSize

ImageSwitch

::

minimumSizeHint

()

const

{

return

QSize

87

28

);

}

void

ImageSwitch

::

setChecked

bool

isChecked

{

if

this

->

isChecked

!=

isChecked

{

this

->

isChecked

=

isChecked

imgFile

=

isChecked

imgOnFile

imgOffFile

this

->

update

();

}

}

void

ImageSwitch

::

setButtonStyle

const

ImageSwitch

::

ButtonStyle

&

buttonStyle

{

if

this

->

buttonStyle

!=

buttonStyle

{

this

->

buttonStyle

=

buttonStyle

if

buttonStyle

==

ButtonStyle_1

{

imgOffFile

=

“:/image/btncheckoff1。png”

imgOnFile

=

“:/image/btncheckon1。png”

this

->

resize

87

28

);

}

else

if

buttonStyle

==

ButtonStyle_2

{

imgOffFile

=

“:/image/btncheckoff2。png”

imgOnFile

=

“:/image/btncheckon2。png”

this

->

resize

87

28

);

}

else

if

buttonStyle

==

ButtonStyle_3

{

imgOffFile

=

“:/image/btncheckoff3。png”

imgOnFile

=

“:/image/btncheckon3。png”

this

->

resize

96

38

);

}

imgFile

=

isChecked

imgOnFile

imgOffFile

setChecked

isChecked

);

this

->

update

();

updateGeometry

();

}

}

三、效果圖

Qt開源作品33-圖片開關控制元件

四、開源主頁

以上作品完整原始碼下載都在開源主頁,會持續不斷更新作品數量和質量,歡迎各位關注。

國內站點:

https://

gitee。com/feiyangqingyu

n/QWidgetDemo

國際站點:

https://

github。com/feiyangqingy

un/QWidgetDemo

個人主頁:

https://

blog。csdn。net/feiyangqi

ngyun

知乎主頁:

https://www。

zhihu。com/people/feiyan

gqingyun/