参考资料:https://blog.csdn.net/qq_31073871/article/details/79851430
comboboxex.h
#ifndef COMBOBOXEX_H
#define COMBOBOXEX_H
#include <QWidget>
#include<QComboBox>
class ComboBoxEx : public QComboBox
{
Q_OBJECT
public:
explicit ComboBoxEx(QWidget *parent = nullptr);
void adjustItemWidth();
signals:
public slots:
};
#endif // COMBOBOXEX_H
comboboxex.c
#include "comboboxex.h"
#include<QAbstractItemView>
ComboBoxEx::ComboBoxEx(QWidget *parent):
QComboBox(parent)
{
}
void ComboBoxEx::adjustItemWidth()
{
int max_len=0;
for(int idx=0;idx < this->count();idx++)
{
if(max_len < this->itemText(idx).length())
max_len = this->itemText(idx).length();
}
int pt_val = this->font().pointSize();//获取字体的磅值
this->view()->setFixedWidth(max_len*pt_val*0.75);//(字符数*每个字符的宽度(磅)*0.75)个像素
}
mainwindow.c
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "commonfunction.h"
#include "comboboxex.h"
#include <QDebug>
#include <QSerialPortInfo>
#define debug qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]" // 调试
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 智能识别当前系统的有效串口号
QList<QSerialPortInfo> serialPortInfo = QSerialPortInfo::availablePorts();
int count = serialPortInfo.count();
for(int i = 0; i<count; i++)
{
// serialPortInfo.at(i).portName() 获取端口号
// serialPortInfo.at(i).description() 获取端口号描述
QString comStr = QString("%1 %2").arg(serialPortInfo.at(i).portName())
.arg(serialPortInfo.at(i).description());
ui->comPortName->addItem(comStr);
debug << serialPortInfo.at(i).description();
}
ui->comPortName->adjustItemWidth(); // 设置下拉框的宽度跟随内容变化
}
MainWindow::~MainWindow()
{
delete ui;
}
......
将端口号的下拉框提升为自定义的ComboBoxEx类