|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#include <QApplication> #include <QMainWindow> #include <QWebEngineView> #include <QLineEdit> #include <QVBoxLayout> #include <QPushButton> class Browser : public QMainWindow { Q_OBJECT public: Browser() { // Create main widget and layout QWidget *mainWidget = new QWidget(this); QVBoxLayout *layout = new QVBoxLayout(mainWidget); // Create URL input field urlField = new QLineEdit(this); urlField->setPlaceholderText("Enter URL"); // Create web view webView = new QWebEngineView(this); // Create navigation button QPushButton *goButton = new QPushButton("Go", this); // Connect button click to URL loading connect(goButton, &QPushButton::clicked, this, &Browser::loadUrl); // Add widgets to layout layout->addWidget(urlField); layout->addWidget(goButton); layout->addWidget(webView); // Set the layout and central widget mainWidget->setLayout(layout); setCentralWidget(mainWidget); setWindowTitle("Basic Web Browser"); resize(1024, 768); } private slots: void loadUrl() { QString url = urlField->text(); if (!url.startsWith("http://") && !url.startsWith("https://")) { url.prepend("http://"); } webView->setUrl(QUrl(url)); } private: QLineEdit *urlField; QWebEngineView *webView; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); Browser browser; browser.show(); return app.exec(); } |
Explanation
- Include Qt Headers:
#include <QApplication>: Manages application-wide resources and settings.#include <QMainWindow>: Provides a main application window.#include <QWebEngineView>: Displays web content. (RequiresQt WebEnginemodule)#include <QLineEdit>: Provides a text input field.#include <QVBoxLayout>: Layout manager for arranging widgets vertically.#include <QPushButton>: Provides a clickable button.
- Browser Class:
- Inherits from QMainWindow: Allows creation of a main application window.
- Widgets:
QLineEdit *urlField: Input field for URL entry.QWebEngineView *webView: Displays web content.QPushButton *goButton: Button to load the URL.
- Constructor:
- Initializes and sets up the main window layout.
- Adds the
urlField,goButton, andwebViewto the layout. - Connects the
goButtonclick signal to theloadUrlslot.
- loadUrl():
- Retrieves the URL from
urlField. - Prepends “http://” if the URL does not start with “http://” or “https://”.
- Loads the URL into
webView.
- Retrieves the URL from
- Main Function:
- Initializes a
QApplicationinstance. - Creates and shows an instance of the
Browserclass. - Enters the Qt event loop using
app.exec().
Notes:
- Qt Installation: Ensure you have Qt and
Qt WebEngineinstalled. - Web Engine Module: The
QWebEngineViewrequires theQt WebEnginemodule, which may need to be installed separately.
- Qt Installation: Ensure you have Qt and
- Initializes a
