如何防止 QSpinBox 自动高亮内容

8

QSpinBox在使用上下按钮时会使其内容被选中(高亮)。有没有办法禁用这个功能?除了使用我自己的QSpinBox子类来访问底层的QLineEdit之外,还有没有其他方法清除选择?

2个回答

11

无法直接禁用它,但您可以进行一些解决方式:

void Window::onSpinBoxValueChanged() // slot
{
    spinBox->findChild<QLineEdit*>()->deselect();
}

我建议使用排队连接(queued connection)来连接到它,就像这样:

connect(spinBox, SIGNAL(valueChanged(int)), this, SLOT(onSpinBoxValueChanged()), Qt::QueuedConnection);

这将确保在高亮显示行编辑器之后调用插槽。


2

与@Anthony的解决方案相同,但更短:

connect(spinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), spinBox,
            [&, spinBox](){spinBox->findChild<QLineEdit*>()->deselect();}, Qt::QueuedConnection);

谢谢,但这是一个重复的答案(除了它使用了新的连接语法与lambda,这在撰写时不可用)。 - Violet Giraffe
我同意,但仍然值得发布。 - Adriel Jr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接