QComboBox是下拉列表框组件类,QPlainTextEdit是一个多行文本编辑器。
添加具有用户数据的项 QComboBox::addltem() 函数的两种参数的原型定义如下:
void addItem (const QString &text, const QVariant &userData = QVariant())
void addItem (const QIcon &icon, const QString &text, const QVariant &userData = QVariant())
不管是哪一个 addItem() 函数,后面都有一个可选的 QVariant 类型的参数 userData,可以利用这个变量存储用户定义数据。
添加图标文件夹
在项目上右键,‘Add New’-》‘Qt’-》‘Qt Resource File’-》‘choose’-》‘名称’-》‘下一步’-》‘完成’;
在‘Resource’下会生成一个‘名称.qrc’,右键‘Add Prefix’-》输入'/' -》‘yes to All’-》右键‘**.qrc’-》‘添加现有文件(选择指定文件夹下所有或单个图标)’-》‘yes to All’;
获取ico图标路径:右键图标,选择‘Copy Path...’。
设置PlainTextEdit的只读属性:
ui->plainTextEdit->setReadOnly(checked);
设置ComboBox的可编辑:
ui->comboBox->setEditable(checked);
界面如下:
//头文件
#ifndef WIDGET_H
#define WIDGET_H#include
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = nullptr);~Widget();private slots:void on_btnIniItems_clicked();void on_btnIni2_clicked();void on_comboBox_currentIndexChanged(const QString &arg1);void on_comboBox_2_currentIndexChanged(const QString &arg1);void on_btnToComboBox_clicked();void on_plainTextEdit_customContextMenuRequested(const QPoint &pos);void on_btnClearText_clicked();void on_enableEdit_clicked(bool checked);void on_readOnly_clicked(bool checked);private:Ui::Widget *ui;
};#endif // WIDGET_H
cpp文件:
#include "widget.h"
#include "ui_widget.h"
#include
#include
{ui->setupUi(this);
}Widget::~Widget()
{delete ui;
}void Widget::on_btnIniItems_clicked()
{QIcon icon;icon.addFile(":/images/icons/cityscape.ico");ui->comboBox->clear();
// for (int i &#61; 0;i <20;i&#43;&#43;){
// ui->comboBox->addItem(icon,QString::asprintf("Ttem %d",i));
// }QStringList strList;strList<
}void Widget::on_btnIni2_clicked()
{QMap
}void Widget::on_comboBox_currentIndexChanged(const QString &arg1)
{ui->plainTextEdit->appendPlainText(arg1);
}void Widget::on_comboBox_2_currentIndexChanged(const QString &arg1)
{QString zone &#61; ui->comboBox_2->currentData().toString();ui->plainTextEdit->appendPlainText(arg1&#43;QStringLiteral("&#xff1a;区号")&#43;"0"&#43;zone);
}void Widget::on_btnToComboBox_clicked()
{QTextDocument *doc &#61; ui->plainTextEdit->document();int cnt &#61; doc->blockCount();QIcon icon(":/images/icons/cityscape.ico");ui->comboBox->clear();for (int i&#61;0;i
}void Widget::on_plainTextEdit_customContextMenuRequested(const QPoint &pos)
{QMenu *menu &#61; ui->plainTextEdit->createStandardContextMenu();menu->exec(pos);
}void Widget::on_btnClearText_clicked()
{ui->plainTextEdit->clear();
}void Widget::on_enableEdit_clicked(bool checked)
{ui->comboBox->setEditable(checked);
}void Widget::on_readOnly_clicked(bool checked)
{ui->plainTextEdit->setReadOnly(checked);
}