我想创建一个具有固定标题的PyQt组合框。更具体地说,这意味着我想要一个下拉菜单,用户可以从中选择,但下拉按钮始终标记为相同。因此,例如,我想为用户创建一个选项,以指定绘制图表的图例的位置。此按钮应始终标记为“图例”,但当您单击它时,它会打开一个下拉菜单,其中包含“右上角”,“左上角”,“顶部”等放置选项。一旦用户选择了选项图例已更新,但按钮仍然是“图例”。 到目前为止我有这个:
self.fnLegendButton = QtGui.QComboBox()
self.fnLegendButton.addItems('Upper right,Lower right,Upper left,Lower left,Top,Disable'.split(','))
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.setToolTip('Select the legend position.')
self.fnLegendButton.currentIndexChanged.connect( <positioning function> )
self.fnLegendButton.setMaximumWidth(60)
答案 0 :(得分:1)
这是一个有效的例子:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.fnLegendButton = QtGui.QComboBox(self)
self.fnLegendButton.addItems(
'Legend,Upper right,Lower right,Upper left,Lower left,Top,Disable'.split(','))
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.setToolTip('Select the legend position.')
self.fnLegendButton.currentIndexChanged[
str].connect(self.avoid_db_change)
self.fnLegendButton.setMaximumWidth(100)
self.fnLegendButton.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('QtGui.QCheckBox')
self.show()
def avoid_db_change(self, text):
print("Processing {0} item".format(text))
self.fnLegendButton.blockSignals(True)
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.blockSignals(False)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
这段代码的重要部分位于avoid_db_change中,该函数用于保存&#34; Legend&#34;文本,无论你按哪个项目。现在,您不想在执行self.fnLegendButton.setCurrentIndex(0)
时再次触发该功能,所以为了避免这种情况,您可以通过几种blockSignals方法将其包围起来。只是尝试评论blockSignals方法,你就会明白这意味着什么。