gpt4 book ai didi

c++ - Qt C++ GUI QSpinBox 存储输入?

转载 作者:行者123 更新时间:2023-11-28 07:09:40 24 4
gpt4 key购买 nike

我如何从旋转框获取用户输入并将其用作值?换句话说,如果我想将 QSpinBox 的输入存储到一个变量中,我该怎么做。我真的是 Qt GUI 的新手,所以任何输入都将不胜感激。

最佳答案

要对 Qt 中的 GUI 元素使用react,您需要连接到这些元素发出的信号。此外,如果您有一个指向它的实例的指针,您可以查询和更改它的状态和属性。

这是您要查找的内容的简单示例

#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include <QSpinBox>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

// The widget, contains a layout
QWidget * w;
w = new QWidget;

// The layout arranges and holds
// all the children of the widget
QVBoxLayout * vbox;

vbox = new QVBoxLayout;

// The user input element, the spinbox!
QSpinBox * spinbox;

spinbox = new QSpinBox();
spinbox->setValue(5);// example of using a pointer to edit its states

// now add it to the layout
vbox->addWidget(spinbox);

// add in an element to connect to,
// the infamous QLabel
QLabel * label;

label = new QLabel("spinbox output");

// add it also to the layout
vbox->addWidget(label);

// connection can happen anytime as long as the two elements
// are not null!

// This connection takes advantage of signals and slots
// and making their connection at runtime.

// if a connect call fails you should be able to see why in the
// application output.
QObject::connect(spinbox, SIGNAL(valueChanged(QString)),
label, SLOT(setText(QString)));

// associate the layout to the widget
w->setLayout(vbox);

// make the widget appear!
w->show();

return a.exec();
}

我通常将大部分 GUI 元素的初始化和连接放在主要 QWidgetQMainWindow 的构造函数或方法中。我经常从 GUI 输入元素(如旋转框)获取信号,然后将其连接到在我的子类 QWidget 上定义的自定义插槽。然后,如果我想用不同的输入值显示它或将输出增加 2,我可以轻松做到。

// in the constructor of my Widget class
// after spinbox has been initialized
QObject(m_spinbox, SIGNAL(valueChanged(int)),
this, SLOT(on_spinboxValueChanged(int)));

void Widget::on_spinboxValueChanged(int i)
{
// here m_label is a member variable of the Widget class
m_label->setText(QString::number(i + 2));

// if accessing the value in this function is inconvenient, you can always
// use a member variable pointer to it to get its stored value.
// for example:
int j = m_spinbox->value();
qDebug() << "Spinbox value" << j;
}

在 QML 和 Qt Quick 中可以完成相同的事情,而且对于许多人来说,它更容易、更直观,因为它与 javascript 和 css 非常接近。

Qt Creator 也有一个用于生成表单的工具,它提供了另一种方法来创建带有布局的小部件,然后当您访问您的元素时,您可以通过 ui 变量来完成。

Qt 文档和示例也很棒。花时间学习和阅读它们是非常值得的。

希望对您有所帮助。

关于c++ - Qt C++ GUI QSpinBox 存储输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21211728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com