Qt 如何使只有一个字段的QComboBox可编辑?
我想制作一个Qt 如何使只有一个字段的QComboBox可编辑?,qt,qcombobox,eventfilter,Qt,Qcombobox,Eventfilter,我想制作一个QComboBox,允许您选择值或输入自己的值。这样,如果选择“可编辑”选项并输入文本,将成为该选项的文本。如果选择“其他”,然后返回“可编辑”,则输入的文本应保持不变 我已经取得了一些进展。看起来是这样的: 组合框菜单 选定的可编辑项 已选择正常项目 我使用事件过滤器实现了这一点: class MagicComboBoxEventFilter : public QObject { public: explicit MagicComboBoxEventFilter(QO
QComboBox
,允许您选择值或输入自己的值。这样,如果选择“可编辑”选项并输入文本,将成为该选项的文本。如果选择“其他”,然后返回“可编辑”,则输入的文本应保持不变
我已经取得了一些进展。看起来是这样的:
组合框菜单
选定的可编辑项
已选择正常项目
我使用事件过滤器实现了这一点:
class MagicComboBoxEventFilter : public QObject {
public:
explicit MagicComboBoxEventFilter(QObject* parent=0) :
QObject(parent),
parentBox(nullptr),
lastValue(""),
editableIndex(-1)
{
parentBox = dynamic_cast<QComboBox*>(parent);
if(parentBox) {
connect(parentBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &MagicComboBoxEventFilter::currentIndexChanged);
}
public slots:
void currentIndexChanged(int index) {
// Item data entry is unused, so I used it to determine
// the editable field from others
bool editable = parentBox->itemData(index).toInt()==666;
parentBox->setEditable(editable);
}
private:
QComboBox* parentBox;
};
我面临的问题是,即使用户选择了其他项,如何保持可编辑值。我尝试连接可编辑文本更改事件,这是我的增强事件过滤器。我不会重复整个类代码,唯一的事情是现在有额外的connect
调用构造函数:
public slots:
void currentIndexChanged(int index) {
bool editable = parentBox->itemData(index).toInt()==666;
parentBox->setEditable(editable);
// If editable field selected, restore the last value entered
if(editable) {
parentBox->setItemText(index, lastValue);
}
}
// slot connected in constructor
void editTextChanged(const QString& text) {
lastValue = text;
}
private:
QComboBox* parentBox;
// Last string value the editable field had
// qt doesn't remember that
QString lastValue;
问题是,当用户选择其他项目时,在CurrentIndexchange之前触发editTextChanged,并且我最终在lastValue
中拥有所选项目的文本,而不是最后输入的文本
如何绕过这一点?我真的很努力,我需要一些帮助。嗯,我也想要同样的东西,但我觉得很简单(对不起,python语法): 基本上,只需将
insertPolicy
设置为InsertAtCurrent
,并通过设置editable
属性对每个currentIndexChanged
做出反应。我使用---
作为可编辑字段的标记,并设置以下项目:
cb = EditableComboBox()
cb.addItem('', '----')
cb.addItem('One', '1')
cb.addItem('Two', '2')
cb.addItem('Three', '3')
另外,当您更改文本时,必须按enter键使其保持不变,否则,如果您选择其他项目,文本将丢失。可能通过获取QComboBox(QStandardItemModel)的子项,然后在此子项上安装另一个事件过滤器?我没有时间测试你的代码,但是这个问题的答案可能会让我感兴趣
class EditableComboBox(QComboBox):
def __init__(self):
QComboBox.__init__(self)
self.currentIndexChanged.connect(self.fix)
self.setInsertPolicy(QComboBox.InsertAtCurrent)
def fix(self, index):
if (self.currentData() == '----'):
self.setEditable(True)
else:
self.setEditable(False)
cb = EditableComboBox()
cb.addItem('', '----')
cb.addItem('One', '1')
cb.addItem('Two', '2')
cb.addItem('Three', '3')