我需要在QSpinBox
中绘制破折号而不是null。另外,我需要使破折号键按下等于空键按下。
我该怎么做?
最佳答案
您可以使用setSpecialValueText()
;
QSpinBox spinBox;
spinBox->setSpecialValueText(tr("-"));
然后您可以通过连接valueChanged(QString)
函数来检查是否选择了特殊值。请注意,这与 valueChanged(int)
不同,您可以检查插槽中传递的字符串的值,如果它等于特殊文本,则可以执行某些操作。
main()
{
connect(spinBox, SIGNAL(valueChanged(QString)), this, SLOT(doSomething(QString)));
}
void doSomething(QString valueStr)
{
if(valueStr == spinBox->specialValueText())
// Do something
else
//Convert valueStr to int and do other stuff
}
或者你可以这样做:
main()
{
connect(spinBox, SIGNAL(valueChanged()), this, SLOT(doSomething()));
}
void doSomething()
{
if(spinBox->value() == 0)
// Do something with dash
else
//Do something with the value
}
对于您的其他问题,您需要创建一个 keyPressEvent 并检查按下的键是否是破折号。如果是破折号,您可以调用另一个函数来执行某些操作。编辑:顺便说一句,specialValueText()
的索引是 0。
编辑:或者您可以在主函数中创建一个QShortcut
。
new QShortcut(QKeySequence(Qt::Key_Minus), this, SLOT(doSomething()));
编辑继续:doSomething() 是一个槽函数。例如,将 void doSomething();
放入头文件的 private slot:
部分。并在cpp文件中定义一个类似这样的函数:
void MainWindow::doSomething()
{
ui->spinBox->setValue(0);
//This is the slot called when you press dash.
}
编辑仍在继续:
您需要在 header 中声明一个 protected:
函数,如下所示:
virtual void keyPressEvent(QKeyEvent *event);
然后你需要在你的cpp文件中定义这个函数。像这样:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Minus)
ui->spinBox->setValue(0);
}
您不必为此功能连接任何信号或插槽。这是一个事件。
这意味着当按下破折号时 ui->spinBox->setValue(0);
因此,您需要创建一个范围从 0 开始的 spinBox。
spinBox->setRange(0, 100);
这意味着,
if(spinBox->value() == 0)
//Then specialValueText is selected.
关于qt - 如何在 QSpinBox 中绘制破折号而不是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28381953/