def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.DrawChessBoard(qp) self.Draw_Chess(qp) qp.end()
pyqt的畫圖機制是:ide
每次界面更新時,自動調用 paintEvet(self,e)函數,因此將繪圖的地方重寫與該函數內。首先得到畫筆,而後在begin方法h和end方法之間,執行繪圖方法。可是,這裏有個問題,我每次界面更新都會調用該方法,可是咱們並非每次都想執行繪製的的東西。好比我這裏有兩個函數:繪製棋盤和繪製棋子。每次我都須要繪製棋盤,可是不是每次都須要繪製棋盤。怎麼辦呢?設置繪製開關。我設置一個變量,經過if 進入不一樣的繪製函數。函數
補充這兩個繪製函數:ui
def DrawChessBoard(self,qp): qp.setPen(QtCore.Qt.black) spos = [0, 0] epos = [0, 0] i = 0 # 畫橫線 while i < 15: spos[0] = self.startpos[0] spos[1] = self.startpos[1] + self.linelen * i epos[0] = self.startpos[0] + self.linelen * 14 epos[1] = self.startpos[1] + self.linelen * i # print i, spos, '--->', epos #self.drawText(str(15 - i), spos[0] - 25, spos[1], 20) qp.drawText(spos[0] - 35, spos[1], QString(str(15-i))) qp.drawLine( spos[0], spos[1], epos[0], epos[1]) i += 1 i = 0 while i < 15: spos[0] = self.startpos[0] + self.linelen * i spos[1] = self.startpos[1] epos[0] = self.startpos[0] + self.linelen * i epos[1] = self.startpos[1] + self.linelen * 14 #self.drawText((self.ch[i]), epos[0], epos[1] + 20, 20) qp.drawText(epos[0], epos[1] + 30, QString(self.ch[i])) qp.drawLine(spos[0], spos[1], epos[0], epos[1]) i += 1
def Draw_Chess(self,qp): self.color=[QtCore.Qt.blue,QtCore.Qt.black,QtCore.Qt.white] self.putOneChess=False #print u'畫一個棋子在棋盤' for point in self.PlayArr: arr_i,arr_j,chessKind=point pos_x,pos_y=self.Arr_To_Pos(arr_i,arr_j) #反走樣 qp.setRenderHint(QPainter.Antialiasing, True) #設置畫筆顏色、寬度 #qp.setPen(QPen(QColor(0, 0, 0), 2)) #設置畫刷顏色 qp.setBrush(self.color[chessKind]) # 繪製圓 qp.drawEllipse(QPointF(pos_x, pos_y),15, 15) if len(self.PlayArr)>0: point =self.PlayArr[-1] arr_i, arr_j, chessKind = point pos_x, pos_y = self.Arr_To_Pos(arr_i, arr_j) # 反走樣 qp.setRenderHint(QPainter.Antialiasing, True) # 設置畫筆顏色、寬度 # qp.setPen(QPen(QColor(0, 0, 0), 2)) # 設置畫刷顏色 qp.setBrush(QtCore.Qt.red) # 繪製圓 qp.drawEllipse(QPointF(pos_x, pos_y), 5, 5) if len(self.virPlayArr)>0: for point in self.virPlayArr: arr_i, arr_j, chessKind = point pos_x, pos_y = self.Arr_To_Pos(arr_i, arr_j) # 反走樣 qp.setRenderHint(QPainter.Antialiasing, True) # 設置畫筆顏色、寬度 # qp.setPen(QPen(QColor(0, 0, 0), 2)) # 設置畫刷顏色 qp.setBrush(QtCore.Qt.blue) # 繪製圓 qp.drawEllipse(QPointF(pos_x, pos_y), 15, 15)