参考资料:https://blog.csdn.net/qq_31073871/article/details/79851430

comboboxex.h

  1. #ifndef COMBOBOXEX_H
  2. #define COMBOBOXEX_H
  3. #include <QWidget>
  4. #include<QComboBox>
  5. class ComboBoxEx : public QComboBox
  6. {
  7. Q_OBJECT
  8. public:
  9. explicit ComboBoxEx(QWidget *parent = nullptr);
  10. void adjustItemWidth();
  11. signals:
  12. public slots:
  13. };
  14. #endif // COMBOBOXEX_H

comboboxex.c

  1. #include "comboboxex.h"
  2. #include<QAbstractItemView>
  3. ComboBoxEx::ComboBoxEx(QWidget *parent):
  4. QComboBox(parent)
  5. {
  6. }
  7. void ComboBoxEx::adjustItemWidth()
  8. {
  9. int max_len=0;
  10. for(int idx=0;idx < this->count();idx++)
  11. {
  12. if(max_len < this->itemText(idx).length())
  13. max_len = this->itemText(idx).length();
  14. }
  15. int pt_val = this->font().pointSize();//获取字体的磅值
  16. this->view()->setFixedWidth(max_len*pt_val*0.75);//(字符数*每个字符的宽度(磅)*0.75)个像素
  17. }

mainwindow.c

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include "commonfunction.h"
  4. #include "comboboxex.h"
  5. #include <QDebug>
  6. #include <QSerialPortInfo>
  7. #define debug qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]" // 调试
  8. MainWindow::MainWindow(QWidget *parent) :
  9. QMainWindow(parent),
  10. ui(new Ui::MainWindow)
  11. {
  12. ui->setupUi(this);
  13. // 智能识别当前系统的有效串口号
  14. QList<QSerialPortInfo> serialPortInfo = QSerialPortInfo::availablePorts();
  15. int count = serialPortInfo.count();
  16. for(int i = 0; i<count; i++)
  17. {
  18. // serialPortInfo.at(i).portName() 获取端口号
  19. // serialPortInfo.at(i).description() 获取端口号描述
  20. QString comStr = QString("%1 %2").arg(serialPortInfo.at(i).portName())
  21. .arg(serialPortInfo.at(i).description());
  22. ui->comPortName->addItem(comStr);
  23. debug << serialPortInfo.at(i).description();
  24. }
  25. ui->comPortName->adjustItemWidth(); // 设置下拉框的宽度跟随内容变化
  26. }
  27. MainWindow::~MainWindow()
  28. {
  29. delete ui;
  30. }
  31. ......

将端口号的下拉框提升为自定义的ComboBoxEx类
image.png

comboboxex.h
comboboxex.cpp
DevConfig.zip