Qt | QComboBox点击时自动更新列表(自动刷新QSerialPort)

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();
}

如果是PyQt,将.ui文件转为py文件后,在该python文件中找到QComboBox进行替换:


方法二

方法一的实现需要修改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…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

觉皇嵌入式

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值