使用signal and slots
方法来获取QcomboBox
中选定项目的索引和文本是众所周知的。下面的代码对此进行了说明。但是如何在启动时告诉我的代码接收并发送第一个显示项,Activated, currentIndexChanged, Highlighted
之类的方法只能通过下拉QCombobox
来工作。
输出:
1
item2
2
item3
示例代码:
from PyQt5 import QtCore, QtWidgets, QtGui
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setLayout(QtWidgets.QVBoxLayout())
combo = QtWidgets.QComboBox(self)
self.layout().addWidget(combo)
combo.addItems(["item1", "item2", "item3"])
combo.setMinimumWidth(150)
combo.activated[int].connect(self.onActivatedIndex)
combo.activated[str].connect(self.onActivatedText)
@QtCore.pyqtSlot(int)
def onActivatedIndex(self, index):
print(index)
@QtCore.pyqtSlot(str)
def onActivatedText(self, text):
print(text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
您可以制作自己的自定义信号,并在对象的__init__
部分中发出该信号。然后,该信号可以访问QComboBox
中的第一项。另一种方法可能是使用singleShot计时器,但制作自定义信号可能会更好。您可以使用currentIndex()
或currentText()
检索当前索引。
from PyQt5 import QtCore, QtWidgets, QtGui
class Widget(QtWidgets.QWidget):
startup = QtCore.pyqtSignal()
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setLayout(QtWidgets.QVBoxLayout())
self.combo = QtWidgets.QComboBox(self)
self.layout().addWidget(self.combo)
self.combo.addItems(["item1", "item2", "item3"])
self.combo.setMinimumWidth(150)
self.combo.activated[int].connect(self.onActivatedIndex)
self.combo.activated[str].connect(self.onActivatedText)
self.startup.connect(self.current_index)
self.startup.emit()
@QtCore.pyqtSlot()
def current_index(self):
print(self.combo.currentIndex())
print(self.combo.currentText())
@QtCore.pyqtSlot(int)
def onActivatedIndex(self, index):
print(index)
@QtCore.pyqtSlot(str)
def onActivatedText(self, text):
print(text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
答案 1 :(得分:0)
尝试一下:
from PyQt5 import QtCore, QtWidgets, QtGui
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setLayout(QtWidgets.QVBoxLayout())
self.combo = QtWidgets.QComboBox(self)
self.layout().addWidget(self.combo)
self.combo.addItems(["item1", "item2", "item3"])
self.combo.setMinimumWidth(150)
self.combo.activated[int].connect(self.onActivatedIndex)
self.combo.activated[str].connect(self.onActivatedText)
self.combo.activated.emit(1) # <---
@QtCore.pyqtSlot(int)
def onActivatedIndex(self, index):
print("\nindex->", index)
print("text ->", self.combo.itemText(index))
@QtCore.pyqtSlot(str)
def onActivatedText(self, text):
print(text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())