【问题标题】:Using a user defined slot in PyQt在 PyQt 中使用用户定义的插槽
【发布时间】:2014-02-10 12:03:18
【问题描述】:

我在使用信号和插槽时遇到问题,使用按钮触发调用“gc.speed_rpm”的事件(使用的已定义插槽,或我自己的方法/函数)并在文本浏览器上显示它的输出小部件。

QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.textBrowser_2, gc.speed_rpm)

我收到以下错误:

arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(),     Qt.ConnectionType=Qt.AutoConnection): argument 4 has unexpected type 'instancemethod'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'QTextBrowser'

会出什么问题?任何想法。

提前致谢。

【问题讨论】:

标签: pyqt


【解决方案1】:

试试这个:

def __init__(self):
  # Connect the clicked action of the push button to a custom slot
  self.pushButton.clicked.connect(self.display_speed_rpm)

def display_speed_rpm(self):
  # Use of setPlainText or setHtml depends on the output of gc.speed_rpm()
  self.textBrowser_2.setPlainText(gc.speed_rpm())

编辑:您还可以使用装饰器方式将小部件信号连接到插槽。您必须根据小部件名称和信号名称来命名您的插槽:

@QtCore.pyqtSlot()
def on_pushButton_clicked(self):
  # Use of setPlainText or setHtml depends on the output of gc.speed_rpm()
  self.textBrowser_2.setPlainText("{}".format(gc.speed_rpm()))

【讨论】:

  • 非常感谢 Frodon,如果我与 self.label.setNum(gc.speed_rpm()) 一起使用,这将有效。至于textBrowser没有这样的“setNum”接口,我应该怎么实现呢,还是typecast呢?
  • @alfa_80:所以我知道 gc.speed_rpm() 返回一个数值。如果速度 rpm 是整数,您可以尝试 setPlainText("%.d"%gc.speed_rpm()),如果速度 rpm 是浮点数并且您需要,则可以尝试 setPlainText("%.4f"%gc.speed_rpm()) 4 位精度,如果您不想精确控制显示,甚至可以使用 setPlainText(str(gc.speed_rpm())。
  • 哇,效果很好!无论如何,我只是想知道为什么期待 QString 的“setPlainText”也可以接受 str(这是本机 python 类型转换)..再次感谢..
  • PyQt 将 Python str 映射为 QString。反之则不然:当您收到一个 QString 时,您可能需要在其上使用 str(theQString) 才能在纯 Python 函数中使用。
猜你喜欢
  • 2013-01-11
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 2013-01-12
  • 2013-09-05
  • 1970-01-01
相关资源
最近更新 更多