Qt | QComboBox点击时自动更新列表(自动刷新QSerialPort)
方法一
实现方法:继承QComboBox,重载showPopup函数。
Python代码:
from PyQt5.Qt import *
class QSerialComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
def showPopup(self):
name = self.currentText()
self.clear()
serials = QSerialPortInfo.availablePorts()
for com in serials:
self.addItem(com.portName() + ' ' + com.description())
super().showPopup()
index = self.findText(name)
if index >= 0:
self.setCurrentIndex(index)
C++代码:
#include "qserialcombobox.h"
#include <QSerialPortInfo>
QSerialComboBox::QSerialComboBox(QWidget *parent) : QComboBox(parent)
{
}
void QSerialComboBox::showPopup()
{
int index = 0;
QString currText = currentText();
// 清除显示
clear();
// 扫描显示可用串口列表
QList<QSerialPortInfo> serials = QSerialPortInfo::availablePorts();
foreach (QSerialPortInfo info, serials) {
addItem(info.portName() + " " + info.description());
}
// 定位显示项
index = findText(currText);
if(index < 0)
{
index = 0;
}
setCurrentIndex(index);
// 调用父类显示列表
QComboBox::showPopup();
}
方法二
方法一的实现需要修改ui_mainwindow.h文件,这个文件只要工程一旦重新构建就会恢复原样,所以又要去修改该文件,比较麻烦,下面介绍第二种方法。
实现方法:利用QComboBox的鼠标点击事件,触发选项更新。
具体方式为覆写主窗体的eventFilter
函数。
在MainWindow头文件中加入:
private slots:
bool eventFilter(QObject *watched, QEvent *event);
然后在MainWindow构造函数中安装QComboBox的事件过滤器:
ui->comboPort->installEventFilter(this);
最后实现该函数:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
{
if(watched == ui->comboPort)
{
QComboBox* comboBox = qobject_cast<QComboBox *>(watched);
comboBox->clear();
QList<QSerialPortInfo> serials = QSerialPortInfo::availablePorts();
foreach (QSerialPortInfo info, serials)
{
comboBox->addItem(info.portName());
}
}
}
return QMainWindow::eventFilter(watched, event);
}
ends…