在 QComboBox
中,你可以使用 count()
方法来获取当前项的数量。该方法返回一个整数,表示组合框中的项目数量。
下面是一个简单的示例代码,展示如何获取和打印 QComboBox
的项数:
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QComboBox>
#include <QPushButton>
#include <QMessageBox>
class MyWidget : public QWidget {
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
QVBoxLayout *layout = new QVBoxLayout(this);
comboBox = new QComboBox(this);
comboBox->addItems({"Item 1", "Item 2", "Item 3"});
QPushButton *button = new QPushButton("Show Item Count", this);
connect(button, &QPushButton::clicked, this, &MyWidget::showItemCount);
layout->addWidget(comboBox);
layout->addWidget(button);
setLayout(layout);
}
private slots:
void showItemCount() {
int itemCount = comboBox->count();
QMessageBox::information(this, "Item Count", QString("The combo box has %1 items.").arg(itemCount));
}
private:
QComboBox *comboBox;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyWidget widget;
widget.resize(300, 100);
widget.show();
return app.exec();
}
#include "main.moc"
示例说明:
- 创建一个
QComboBox
并添加了一些项。 - 添加了一个按钮,当点击时会触发
showItemCount()
槽函数。 - 在槽函数中,调用
comboBox->count()
获取项目的数量,并通过信息框显示出来。
这样你就可以轻松获取并使用 QComboBox
中项的数量了。
内容由零声教学AI助手提供,问题来源于学员提问