【问题标题】:Use custom image in QCursor在 QCursor 中使用自定义图像
【发布时间】:2017-04-03 09:19:57
【问题描述】:

我有一个 .bmp 图像,我想将它用作我的 GUI 的光标。 QCursor Documentation 建议这是可能的(“要使用您自己的位图创建光标,请使用采用位图和掩码的 QCursor 构造函数或采用像素图作为参数的构造函数”)但我似乎不能当我尝试将建议的模块与我的位图一起使用时,让它工作,因为我得到 'TypeError: QCursor(): argument 1 has unexpected type 'str''。这应该怎么做?

下面是产生上述错误的代码。文档还建议将 alpha 掩码和其他两个值传递给 QCursor,但我不确定这些是否必要,如果需要,它们应该是什么。

import sys
from PyQt4 import QtGui, QtCore

QtGui.QCursor('image.bmp')

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        cursor = QtGui.QPixmap('image.bmp')
        self.setCursor(QtGui.QCursor(cursor))
        self.home()

    def home(self):
        btn = QtGui.QPushButton("Quit", self)
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        btn.resize(100,100)
        btn.move(100,100)
        self.show()


def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

【问题讨论】:

  • 你能给我们一些代码吗?作为一个赌注,我会说您将 bmp 的路径字符串直接提供给 QCursor 构造函数。如果是这样,请尝试在两者之间调用 QPixmap 构造函数。
  • 我在查询中添加了一个基本的 GUI - 在这种情况下,任何事情都可以用于图像。
  • 感谢您的代码。你能用'image.bmp'路径实例化一个QPixmap,把它交给QtGui.QCursor构造函数,然后把后者交给一个小部件,让我们在init中说'self',通过setCursor?
  • 谢谢 - 光标出现了,但尽管在 Photoshop 中删除了背景,但仍然出现白色背景。
  • 呃。你是怎么做到的?我不记得 BMP 可以对透明度进行编码,但我在谷歌搜索时读到了其他内容。你能更新代码吗?

标签: python image pyqt qcursor


【解决方案1】:

如果它可以帮助任何人通过谷歌搜索到这里,并且你可以给whatEverColor 赋值为透明颜色。在__init__

pm = QtGui.QPixmap('image.bmp')
bm = pm.createMaskFromColor(whatEverColor, Qt.MaskOutColor)
pm.setAlphaChannel(bm)
cursor = QtGui.QCursor(pm)
self.setCursor(cursor)

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2012-11-18
    • 2013-01-05
    • 2021-10-21
    • 2013-06-13
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多