QT开发中文网

可以在QWidget中添加这个标题栏吗?不是QMainWindow

是的,你可以在QWidget中添加自定义标题栏。以下是修改后的示例代码:

#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;
};

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

    QWidget window;
    
    QVBoxLayout* layout = new QVBoxLayout(&window);
    
    CustomTitleBar* titleBarWidget = new CustomTitleBar(&window);
    layout->addWidget(titleBarWidget); // 将自定义标题栏添加到布局中
    
    QWidget* contentWidget = new QWidget(&window); // 添加其他内容部件
    contentWidget->setStyleSheet("background-color: #ffffff;");
    
    layout->addWidget(contentWidget); // 将内容部件添加到布局中

    QObject::connect(titleBarWidget, &CustomTitleBar::optionSelected,
                     [&](const QString& option) { qDebug() << "Selected option:" << option; });

    window.show();

    return app.exec();
}

在这个修改后的示例代码中,我们将自定义标题栏 CustomTitleBar 添加到一个QWidget窗口的布局中。并且添加了一个内容部件 contentWidget ,你可以根据需要进行调整和扩展布局。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?