You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python中Qt fillRect的重载调用参数不匹配错误?

问题分析与解决

错误原因

报错是因为调用QPainter.fillRect时传入的参数不符合任何重载版本:

TypeError: arguments did not match any overloaded call:
fillRect(self, QRectF, Union[QBrush, QColor, Qt.GlobalColor, int, QGradient]): argument 1 has unexpected type 'int'

你现在分两次调用fillRect,每次只传两个int参数(比如painter.fillRect(col,row)),但fillRect没有这种参数形式的重载。它的常用重载是:

  • fillRect(int x, int y, int width, int height):传入矩形的左上角坐标和宽高
  • fillRect(QRectF rect):传入一个QRectF对象

代码修正

你的代码逻辑是通过translate把坐标系移到每个格子的左上角,所以只需要画一个从(0,0)开始,宽高为格子尺寸的矩形即可,不需要分开调用两次fillRect。同时优化棋盘颜色切换的逻辑(原逻辑会导致每行颜色交替混乱,应该用行+列的奇偶性判断):

def drawBoardSquares(self, painter):
    '''draw all the square on the board'''
    # 设置默认画刷
    brush = QBrush(Qt.BrushStyle.SolidPattern)
    orange = QColor(245, 173, 66)
    gray = QColor(110, 110, 110)

    for row in range(Board.boardHeight):
        for col in range(Board.boardWidth):
            painter.save()
            # 计算格子的偏移量并移动坐标系
            col_trans = self.squareWidth() * col
            row_trans = self.squareHeight() * row
            painter.translate(col_trans, row_trans)

            # 根据行+列的奇偶性设置画刷颜色
            if (row + col) % 2 == 0:
                brush.setColor(orange)
            else:
                brush.setColor(gray)
            painter.setBrush(brush)

            # 绘制格子:从(0,0)开始,宽高为当前格子的尺寸
            painter.fillRect(0, 0, self.squareWidth(), self.squareHeight())
            painter.restore()

关键修改点

  • 合并两次错误的fillRect调用,改为传入0, 0, 格子宽, 格子高四个参数,符合重载要求
  • 用row + col的奇偶性判断颜色,确保棋盘是交替的格子颜色(原逻辑每次循环切换颜色会导致同一行相邻格子颜色相同,不符合棋盘样式)
  • 把颜色常量提前定义,避免重复创建QColor对象

内容的提问来源于stack exchange,提问作者Melisa Spivacenco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:15:52