QT开发中文网

Qt 控件放到标题栏,单击可出现列表并选择其中一个选项

要将Qt控件放到标题栏,并实现点击弹出列表选择选项的功能,可以使用自定义窗口标题栏和下拉菜单组合的方式来实现。以下是一个简单的示例代码:

#include <QtWidgets>

class CustomTitleBar : public QWidget {
public:
    CustomTitleBar(QWidget *parent = nullptr) : QWidget(parent) {
        setFixedHeight(30);

        QHBoxLayout *layout = new QHBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);

        QLabel *titleLabel = new QLabel("Custom Title Bar", this);
        layout->addWidget(titleLabel);

        QPushButton *optionsButton = new QPushButton("Options", this);
        connect(optionsButton, &QPushButton::clicked, this, &CustomTitleBar::showOptionsMenu);
        layout->addWidget(optionsButton);

        menu = new QMenu(this);
        menu->addAction("Option 1");
        menu->addAction("Option 2");
    }

signals:
    void optionSelected(const QString &option);

private slots:
    void showOptionsMenu() {
        QAction *selectedAction = menu->exec(QCursor::pos());
        
        if (selectedAction) {
            emit optionSelected(selectedAction->text());
        }
    }

private:
    QMenu *menu;
};

class MainWindow : public QMainWindow {
public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
       CustomTitleBar* titleBarWidget = new CustomTitleBar(this);
       setWindowTitle("");
       setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); // 去除默认标题栏
       
       connect(titleBarWidget, &CustomTitleBar::optionSelected, this, &MainWindow::handleOptionSelected);
       
       setMenuWidget(titleBarWidget); // 设置自定义标题栏
    }
    
private slots:
    void handleOptionSelected(const QString &option) {
        qDebug() << "Selected option:" << option;
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    MainWindow window;
    window.show();

    return app.exec();
}

以上代码演示了如何创建一个自定义的标题栏 CustomTitleBar,并在其中添加一个按钮,点击按钮弹出菜单选项。通过连接 optionSelected 信号和槽函数,在主窗口中处理选项的选择事件。你可以根据需要进行调整和扩展。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9008

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?